setColorFilter not working
I'm trying to implement a simple colorfilter on an imageview to turn the black image into a white image. In order to achieve that I do the following:
weatherImg.setColorFilter(Color.BLACK, PorterDuff.Mode.MULTIPLY);
weatherImg.setImageResource(R.drawable.b_clouded_rain);
I've also tried to change to color in the color filter to red and white but all of them have no effect, what am I doing wrong?
As much as I hate to answer my own questions I found the problem: I should've used:
weatherImg.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
It depends on what kind of filtering you want to apply. If yout want to apply a new color on an image with transparencies on it, that's what worked for me:
weatherImg.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
If you want to learn more about this PorterDuff filters, I found a goog article that helped me understand: http://www.ibm.com/developerworks/java/library/j-mer0918/ give it a read :)
Had the same issue on Android 6. Solved by using ImageView.getDrawable().setColorFilter()
instead of ImageView.setColorFilter()
.
We use this code
Drawable drawable = DrawableCompat.wrap(getDrawable(drawableResource));
drawable.mutate();
DrawableCompat.setTint(drawable, getColor(color));
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
public static int getColor(int id) {
return ContextCompat.getColor(getInstance().context, id);
}
public static Drawable getDrawable(int id) {
return ContextCompat.getDrawable(getInstance().context, id);
}
For me, simply calling setColorFilter()
on the ImageView
wasn't working.
imageView.setColorFilter(ResourcesCompat.getColor(resources, color, null)) //didnt work on 21, only 22+
For whatever reason, on API 21, the only way I could get setColorFilter()
to work properly was to post the change to the views message queue.
imageView.post { imageView.setColorFilter(ResourcesCompat.getColor(resources, color, null)) } //this works on 21+