How to change colors of a Drawable in Android?

前端 未结 21 1879
野性不改
野性不改 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:08
    Int color = Color.GRAY; 
    // or int color = Color.argb(123,255,0,5);
    // or int color = 0xaaff000;
    

    in XML /res/values/color.xml

    <?xml version="1.0" encoding="utf-8">
    <resources>
        <color name="colorRed">#ff0000</color>
    </resoures> 
    

    Java Code

    int color = ContextCompat.getColor(context, R.color.colorRed);
    
    GradientDrawable drawableBg = yourView.getBackground().mutate();
    drawableBg.setColor(color);
    
    0 讨论(0)
  • 2020-11-22 14:12

    This code snippet worked for me:

    PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(getResources().getColor(R.color.your_color),PorterDuff.Mode.MULTIPLY);
    
    imgView.getDrawable().setColorFilter(porterDuffColorFilter);
    imgView.setBackgroundColor(Color.TRANSPARENT)
    
    0 讨论(0)
  • 2020-11-22 14:12

    There are so many solution but nobody suggested if the color resource xml file already have color then we can pick directly from there also as below:

    ImageView imageView = (ImageView) findViewById(R.id.imageview);
    imageView.setColorFilter(getString(R.color.your_color));
    
    0 讨论(0)
  • 2020-11-22 14:13

    I think you can actually just use Drawable.setColorFilter( 0xffff0000, Mode.MULTIPLY ). This would set white pixels to red but I don't think it would affect the transparent pixels.

    See Drawable#setColorFilter

    0 讨论(0)
  • 2020-11-22 14:13

    You can solve it using Android support compat libraries. :)

     // mutate to not share its state with any other drawable
     Drawable drawableWrap = DrawableCompat.wrap(drawable).mutate();
     DrawableCompat.setTint(drawableWrap, ContextCompat.getColor(getContext(), R.color.your_color))
    
    0 讨论(0)
  • 2020-11-22 14:13
    view.getDrawable().mutate().setColorFilter(0xff777777, PorterDuff.Mode.MULTIPLY); 
    

    Thanks to @sabadow

    0 讨论(0)
提交回复
热议问题