Programmatically tint a Support Vector

╄→гoц情女王★ 提交于 2019-11-30 11:37:47

first of all you should use VectorDrawableCompat#create, once you have your Drawable you have to call DrawableCompat#wrap:

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

so your code would look like this:

ImageView iv = ....
Drawable d = VectorDrawableCompat.create(getResources(), R.drawable.ic_exit_to_app_24dp, null);
d = DrawableCompat.wrap(d);
DrawableCompat.setTint(d, headerTitleColor);
iv.setImageDrawable(d);

You can use setColorFilter method of ImageView:

imageView.setColorFilter(headerTitleColor, android.graphics.PorterDuff.Mode.MULTIPLY);

Another handy solution with Kotlin:

fun Context.drawableWithColor(@DrawableRes drawableRes: Int, @ColorInt color: Int): Drawable? {
    val pic = ContextCompat.getDrawable(this, drawableRes)
    pic?.setColorFilter(color, PorterDuff.Mode.SRC_IN)
    return pic
}

Use is as simple as:

val drawable = context.drawableWithColor(R.drawable.your_awesome_drawable, Color.BLUE)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!