javaandroidcolorfilter

ColorFilter only specific color


A short question regarding the ColorFilter() function; I am trying to replace an specific color of an Image with an new color:

Default: default result: result

So in this example I just want to replace the red color with the blue color. But don't modify the black color of this image.

At the moment Iam using the following code:

int color = Color.parseColor("#0000FF"); iv1.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);

From the description of the "PorterDuff" Mode I should use "SRV_ATOP". But how should I use this mode so that only the red color will be replaced?


Solution

  • I've now found a way which works perfectly. So for everyone who faces the same probleme...here is the code which works for me:

                //Decode *.png file to Bitmap
                Bitmap Bitmap_temp = BitmapFactory.decodeResource(getResources(), R.drawable.image_1);
                Bitmap Bitmap_final = Bitmap_temp.copy(android.graphics.Bitmap.Config.ARGB_8888, true);
    
                //Get Pixel and change color if pixel color match
                int [] allpixels = new int [Bitmap_final.getHeight() * Bitmap_final.getWidth()];
                Bitmap_final.getPixels(allpixels, 0, Bitmap_final.getWidth(), 0, 0, Bitmap_final.getWidth(), Bitmap_final.getHeight());
                for(int i = 0; i < allpixels.length; i++)
                {
                    if(allpixels[i] == Color.parseColor("#fff000"))
                    {
                        allpixels[i] = Color.parseColor("#0D0D0D");
                    }
                }
                Bitmap_final.setPixels(allpixels,0,Bitmap_final.getWidth(),0, 0, Bitmap_final.getWidth(),Bitmap_final.getHeight());
    
                //Set Bitmap to ImageView
                iv_image1.setImageBitmap(Bitmap_final);