天天看点

让Drawable变色

做项目的时候有时需要根据点击图片切换不同的图片,这就需要美工切几张不同颜色的图,后来发现有办法可以使drawable变色,这样无形减少很多图片所占的空间,而且想要什么颜色都行。

1.需要android.support.v4 中的DrawableCompat类

2.生成所需要的Drawable,我封装成了个类,方便使用

public class DrawableTintUtil {
       public static Drawable getTintDra(Drawable drawable, ColorStateList colorStateList) {
        Drawable wraDra = DrawableCompat.wrap(drawable);
        DrawableCompat.setTintList(wraDra, colorStateList);
        //防止drawable不显示
        wraDra.setBounds(,,wraDra.getMinimumWidth(),wraDra.getMinimumHeight());

        return wraDra;
    }
}
           

前面参数大家都知道了,关于后面一个参数 colorStateList分两种情况

1.只传入一种颜色,如 R.color.colorPrimary

需要用       
          ColorStateList.valueOf(context.getResources().getColor(R.color.colorPrimary))
  或者
 DrawableCompat.setTint(drawable, context.getResources().getColor(R.color.colorPrimary))直接传入
           

2.传入多种颜色,就是指点击变色选中变色之类的

在value目录下新建 color文件夹,之后在里面建立xml文件

R.color.ic_index_guide_colors

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorPrimary" android:state_selected="true" />
    <item android:color="@color/colorPrimary" android:state_pressed="true" />
    <item android:color="#898989" />
</selector>
           

之后就是简单的获取

ColorStateList colorStateList=getResources().getColorStateList(R.color.ic_index_guide_colors)
           

之后再传入colorStateList ,最后把获取到的Drawable设置进对应的控件中