包含自定义形状的 ShapeDrawable 的 setTint?

setTint of ShapeDrawable containing custom Shape?

在包含自定义 ShapeShapeDrawable 上调用 setTint() 似乎对基础形状的颜色没有影响。

CustomShape.kt

class CustomShape : Shape() {

    private val paint = Paint()
    private val path = Path()

    init {
        paint.isAntiAlias = true
    }

    override fun onResize(width: Float, height: Float) {
        // update path
    }

    override fun draw(canvas: Canvas, paint: Paint) {
        canvas.drawPath(path, this.paint)
    }
}

用法

val shape = CustomShape()
val drawable = ShapeDrawable(shape)
drawable.setTint(Color.RED) // not working
someView.background = drawable

解决方案

使用 draw() 提供的 Paint 对象,它已经应用了反别名标志,并且会尊重您在 ShapeDrawable.

上调用的任何方法

问题是我正在创建和使用新的 Paint 对象,而不是使用 draw() 中提供的对象。这样做的理由是我需要打开 anti-aliasing,我想避免在 draw 方法中这样做。

此外,我最初在 CustomShape 中直接给 Paint 对象一个颜色,然后才意识到可能 better/necessary 让 ShapeDrawable 处理它。