Flutter中SVG <image>的preserveAspectRatio属性失效问题
问题:SVG图片设置
preserveAspectRatio="none"未生效,无法拉伸 用户提供的SVG代码:
<g transform="translate(0,-37.01)" id="g73"> <rect style="opacity:1;fill:#ffffff;fill-rule:nonzero;stroke:none;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" x="-156.06" y="-156.06" rx="22.700001" ry="22.700001" width="312.12" height="312.12" id="rect71"/> </g> <image width="295.91602" height="295.91599" preserveAspectRatio="none" xlink:href="$_profileImage" id="image21342" x="-148.14604" y="-185.1489" style="stroke-width:0;stroke-dasharray:none;paint-order:markers stroke fill"/>
问题说明
设置preserveAspectRatio="none"后,图片仍保持原始比例显示,未按预期拉伸填满下方的白色圆角矩形区域。预期效果为图片忽略原始宽高比,完全拉伸覆盖整个圆角矩形。
解决方案
问题出在image元素的尺寸和位置与目标矩形不匹配,导致即使设置了preserveAspectRatio="none",也无法填满区域。修改image的x、y、width、height属性,使其与下方圆角矩形的参数完全一致:
<g transform="translate(0,-37.01)" id="g73"> <rect style="opacity:1;fill:#ffffff;fill-rule:nonzero;stroke:none;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" x="-156.06" y="-156.06" rx="22.700001" ry="22.700001" width="312.12" height="312.12" id="rect71"/> </g> <image width="312.12" height="312.12" preserveAspectRatio="none" xlink:href="$_profileImage" id="image21342" x="-156.06" y="-156.06" style="stroke-width:0;stroke-dasharray:none;paint-order:markers stroke fill"/>
原理说明
- 将
image的尺寸调整为和圆角矩形一致(312.12x312.12),确保目标区域完全覆盖; - 同步
image的位置参数(x=-156.06,y=-156.06),使其与矩形对齐; - 保留
preserveAspectRatio="none",强制图片拉伸以填满整个区域,忽略原始宽高比。
内容的提问来源于stack exchange,提问作者IshikiHIkaru
相关产品推荐
相关产品推荐

