Change the color balance of Drawable

Can I change the color balance of Drawable?

For example, I would like to convert
enter image description here in => enter image description here

I try this, but it changes 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 indicate I do not want to split the src image into 2 or more layers and colorize one of them.

+5
source share
2 answers

You can apply the hue with the desired color to the image using mutate().setColorFilter() , and set Drawable with the new color to 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 the following image:

enter image description here

You can also use the color defined in your example:

  myImage.mutate().setColorFilter(Color.argb(255, 110, 150, 200), PorterDuff.Mode.MULTIPLY); 
+1
source

I see that your character has eyes and some kind of attribute that should be safe during color changes, so we need more control over this resource, so we will convert it to a bitmap:

 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.brown_man); 

Your bitmap may not change, so to change it:

 Bitmap myBitmap = bitmap.copy(Bitmap.Config.RGB_565, true); 

Then we have to getPixels() and re setPixels() with the given 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()); 

So you can use this bitmap as you want.

Some things to consider:

  • Your resource character must have a color of height resolution in order to simplify its definition and change.
0
source

Source: https://habr.com/ru/post/1274118/


All Articles