android 图片变颜色代码,Android -对图片Drawable进行变色

Android 图片DrawableCompat利用setTint()对图片Drawable进行变色

1.利用color资源对Drawable变色

Drawable对象的来源不限制,可以是从资源getResource().getDrawable(int resourceId)也可以是其他的方式得到的Drawable

Drawable wrappedDrawable = DrawableCompat.wrap(drawable);

DrawableCompat.setTint(wrappedDrawable, color);

2.采用ColorStateList来改变Drawable

Drawable wrappedDrawable = DrawableCompat.wrap(drawable);

DrawableCompat.setTintList(wrappedDrawable, colors);

3.介绍一下ColorStateList

android:color="#ffff0000"/>

android:color="#ff0000ff"/>

Java代码(用于改变按钮的字体颜色)

Button btn=(Button)findViewById(R.id.btn);

Resources resource=(Resources)getBaseContext().getResources();

ColorStateList csl=(ColorStateList)resource.getColorStateList(R.color.button_text);

if(csl!=null){

btn.setTextColor(color_state_list);//设置按钮文字颜色

}

4.安利一个朋友封装的工具类

public class DrawableTintUtil {

/**

* Drawable 颜色转化类

*

* @param drawable

* @param color资源

* @return 改变颜色后的Drawable

*/

public static Drawable tintDrawable(@NonNull Drawable drawable, int color) {

Drawable wrappedDrawable = DrawableCompat.wrap(drawable);

DrawableCompat.setTint(wrappedDrawable, color);

return wrappedDrawable;

}

/**

* Drawable 颜色转化类

*

* @param drawable 源Drawable

* @param ColorStateList

* @return 改变颜色后的Drawable

*/

public static Drawable tintListDrawable(@NonNull Drawable drawable, ColorStateList colors) {

Drawable wrappedDrawable = DrawableCompat.wrap(drawable);

DrawableCompat.setTintList(wrappedDrawable, colors);

return wrappedDrawable;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值