Reputation: 3971
It is possible to change the color balance of a Drawable ?
For example, I would like to convert
to =>
I try this but it change all the colors of my Drawable to one unique color :
Drawable drawable; // my drawable
float r = Color.red(110) / 255f;
float g = Color.green(150) / 255f;
float b = Color.blue(200) / 255f;
ColorMatrix cm = new ColorMatrix(new float[] {
// Change red channel
r, 0, 0, 0, 0,
// Change green channel
0, g, 0, 0, 0,
// Change blue channel
0, 0, b, 0, 0,
// Keep alpha channel
0, 0, 0, 1, 0,
});
ColorMatrixColorFilter cf = new ColorMatrixColorFilter(cm);
drawable.setColorFilter(cf);
I specify I don't want to split my src image into 2 or more layers and colorify one of them.
Upvotes: 4
Views: 219
Reputation:
I can see that your character have eyes and some attribute which need to be safe during color change, so we need more control on that resource therefore we will convert it to bitmap:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.brown_man);
Your bitmap might be not mutable so in order to make it mutable:
Bitmap myBitmap = bitmap.copy(Bitmap.Config.RGB_565, true);
Then we have to getPixels()
And re setPixels()
with specified color:
int[] pixels = new int[myBitmap.getHeight() * myBitmap.getWidth()];
myBitmap.getPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
for (int i = 0; i < pixels.length; i++) {
if (pixels[i] == color /*Color to change int value*/)
pixels[i] = newColor /*The new color you want to change*/;
}
myBitmap.setPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
Thus, you can use this bitmap as you wish.
Some things to take considering:
Upvotes: 0
Reputation: 126455
You can apply a tint with the desired color to your image using mutate().setColorFilter()
, and set the Drawable with the new color into your ImageView:
ImageView imgImagen = (ImageView)findViewById(R.id.myImageView);
Drawable myImage = getResources().getDrawable( R.drawable.boy );
//Using red color.
myImage.mutate().setColorFilter(0xffff0000, PorterDuff.Mode.MULTIPLY);
imgImagen.setImageDrawable(myImage);
For example using this ImageView
,
<ImageView
android:id="@+id/myImageView"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="@drawable/boy"
android:contentDescription="" />
you will have this image as result:
You can use too the color defined in your example:
myImage.mutate().setColorFilter(Color.argb(255, 110, 150, 200), PorterDuff.Mode.MULTIPLY);
Upvotes: 1