How to change colors of a Drawable in Android?

前端 未结 21 2051
野性不改
野性不改 2020-11-22 13:50

I\'m working on an android application, and I have a drawable that I\'m loading up from a source image. On this image, I\'d like to convert all of the white pixels to a dif

21条回答
  •  一生所求
    2020-11-22 14:24

    In your Activity you can tint your PNG image resources with a single colour:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myColorTint();
        setContentView(R.layout.activity_main);
    }
    
    private void myColorTint() {
        int tint = Color.parseColor("#0000FF"); // R.color.blue;
        PorterDuff.Mode mode = PorterDuff.Mode.SRC_ATOP;
        // add your drawable resources you wish to tint to the drawables array...
        int drawables[] = { R.drawable.ic_action_edit, R.drawable.ic_action_refresh };
        for (int id : drawables) {
            Drawable icon = getResources().getDrawable(id);
            icon.setColorFilter(tint,mode);
        }
    }
    

    Now when you use the R.drawable.* it should be coloured with the desired tint. If you need additional colours then you should be able to .mutate() the drawable.

提交回复
热议问题