2025-04-23

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

  
  
       
       
       
  

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;
  }
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *