如何在不修改原始可绘制对象的情况下设置 vectorDrawable 的色调?

How to set tint of vectorDrawable without modifying the original drawable?

我正在尝试在我的视图 class 中使用 SVG 文件,我 运行 遇到的问题是: 当我像这样设置 VectorDrawable 的色调时:

var d = AppCompatResources.getDrawable(context, R.drawable.icon)
var vDraw = VectorDrawable()
vDraw  = d as VectorDrawable
DrawableCompat.setTint(vDraw , Color.RED)
vDraw.draw(canvas)

我最终要修改原始可绘制对象。有没有一种方法可以在不修改原始 SVG 的情况下在代码中执行此操作?

您需要调用 drawable mutate() 方法。来自 documentation:

Make this drawable mutable. This operation cannot be reversed. A mutable drawable is guaranteed to not share its state with any other drawable. This is especially useful when you need to modify properties of drawables loaded from resources. By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification. Calling this method on a mutable Drawable will have no effect.

并且由于您想要为可绘制对象着色,因此还需要使用 DrawableCompat.wrap(drawable)。这将允许:

Potentially wrap {@code drawable} so that it may be used for tinting across the different API levels, via the tinting methods in this class.

将此应用于您的代码:

var drawable = AppCompatResources.getDrawable(context, R.drawable.icon)
drawable = drawable.mutate();
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable , Color.RED)
drawable.draw(canvas)