首页 > 解决方案 > 如何将 Android 渐变渲染与 SVG BoundingBox 单元相匹配

问题描述

我正在尝试使用 LinearGradient 类在 Android 矢量绘图中复制 SVG。对于边界框渐变单元,我使用以下公式计算渐变线段的端点:

x1 = graphic_bound.left + graphic_bound.width() * svg_boundingbox_width_percentage

y1 = graphic_bound.top + graphic_bound.height() * svg_boundingbox_height_percentage

我观察到上述方法适用于以下情况graphic_bound.width() == graphic_bound.height()

但是当图形边界为非正方形(宽度不等于高度)时,渲染与 SVG 不同。

关于这里的错误有什么建议吗?

例如,下面的 SVG 看起来是一样的,一个使用 objectBoundingBox,另一个使用 userSpaceOnUse 单位。我的问题是如何将 objectBoundingBox 值转换为 userSpaceOnUse 值以具有相同的视觉外观?

<svg width="332px" height="112px" viewBox="0 0 500 112" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <title>linear_gradient_direction</title>
    <desc>Created with Sketch.</desc>
    <defs>
        <linearGradient gradientUnits="objectBoundingBox" x1="30.2395833%" y1="44.8925781%" x2="69.9661458%" y2="54.944987%" id="linearGradient-2">
            <stop stop-color="#FFFFFF" offset="0%"></stop>
            <stop stop-color="#000000" offset="51%"></stop>
            <stop stop-color="#D8D8D8" offset="100%"></stop>
        </linearGradient>
        <linearGradient gradientUnits="userSpaceOnUse" x1="60" y1="30" x2="140" y2="70" id="linearGradient-3">
            <stop stop-color="#FFFFFF" offset="0%"></stop>
            <stop stop-color="#000000" offset="51%"></stop>
            <stop stop-color="#D8D8D8" offset="100%"></stop>
        </linearGradient>
    </defs>
    <g id="linear_gradient_direction" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="Rectangle-Box" transform="translate(5.000000, 6.000000)" stroke="#979797">
            <rect id="Rectangle" fill="url(#linearGradient-2)" x="0" y="0" width="200" height="100"></rect>
            <line x1="60" y1="30" x2="140" y2="70" id="Line" stroke-linecap="square"></line>
            <circle id="TopLeft" fill="#FFFFFF" cx="60" cy="30" r="5"></circle>
            <circle id="Center" fill="#FFFFFF" cx="100" cy="50" r="5"></circle>
            <circle id="BottomRight" fill="#FFFFFF" cx="140" cy="70" r="5"></circle>
        </g>
        <g id="Rectangle-Box" transform="translate(220.000000, 6.00000)" stroke="#979797">
            <rect id="Rectangle" fill="url(#linearGradient-3)" x="0" y="0" width="200" height="100"></rect>
            <line x1="60" y1="30" x2="140" y2="70" id="Line" stroke-linecap="square"></line>
            <circle id="TopLeft" fill="#FFFFFF" cx="60" cy="30" r="5"></circle>
            <circle id="Center" fill="#FFFFFF" cx="100" cy="50" r="5"></circle>
            <circle id="BottomRight" fill="#FFFFFF" cx="140" cy="70" r="5"></circle>
        </g>
    </g>
</svg>

标签: androidsvglinear-gradientsvector-graphicsandroid-vectordrawable

解决方案


推荐阅读