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
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);
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)
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));
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
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))
view.getDrawable().mutate().setColorFilter(0xff777777, PorterDuff.Mode.MULTIPLY);
Thanks to @sabadow