【问题标题】:How to fill a ShapeDrawable (containing a PathShape) with a gradient如何用渐变填充 ShapeDrawable(包含 PathShape)
【发布时间】:2012-06-09 17:06:25
【问题描述】:

我在使用可绘制对象的setShaderFactory() 方法填充包含自定义PathShapeShapeDrawable 时遇到问题。以下代码在绘制RectShape 时完美运行:

ShapeDrawable shape = new ShapeDrawable();
shape.setShape(new RectShape());
shape.setShaderFactory(new ShaderFactory() {
    @Override
    public Shader resize(int width, int height) {
        LinearGradient gradient = new LinearGradient (0, 0,
                width, height, Color.Red, Color.Blue,
                TileMode.REPEAT);
        return gradient;
    }
});

当我将RectShape 更改为任何自定义PathShape 时,drawable 仅使用渐变起始颜色(红色)填充整个形状。换句话说,自定义形状绘制正确,但颜色完全错误。有没有人见过这个并且知道可能是什么问题?

【问题讨论】:

    标签: android drawable


    【解决方案1】:

    经过实验发现,渐变的大小必须与PathShape的标准宽度和标准高度有关,在创建时与ShapeDrawable的高度和宽度无关。这意味着您必须在 ShapeDrawable 的整个生命周期内跟踪分配给 PathShape 的标准宽度/高度,以防它被调整大小。

    虽然有些不雅,但这里有一个解决方案:

    public static final int STD_WIDTH = 20;
    public static final int STD_HEIGHT = 20;
    
    PathShape shape = new PathShape(myPath, STD_WIDTH,
            STD_HEIGHT);
    ShapeDrawable drawable = new ShapeDrawable();
    drawable.setShape(myPathShape);
    drawable.setShaderFactory(new ShaderFactory() {
        @Override
        public Shader resize(int width, int height) {
            LinearGradient gradient = new LinearGradient (0, 0,
                    STD_WIDTH, STD_HEIGHT, Color.Red, Color.Blue,
                    TileMode.REPEAT);
            return gradient;
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 2011-11-12
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      相关资源
      最近更新 更多