Search code examples
androidcolorsbitmapcolormatrixporter-duff

Change the bitmap color


There is a bitmap with a white background and an orange triangle inside. What I want to do is change the color of the orange triangle to the color I want, how can I do this with code? I used Porterduff and Color Matrix, but did not get the result I wanted.

Original: click to see the picture

What I want to do with code: click to see the picture

I don't want the white background color to change.


Solution

  • I have used this method to change the color of the bitmap runtime. Give it a try.

     public Bitmap replaceColor(Bitmap src,int fromColor, int targetColor) {
            if(src == null) {
                return null;
            }
         // Source image size 
            int width = src.getWidth();
            int height = src.getHeight();
            int[] pixels = new int[width * height];
            //get pixels
            src.getPixels(pixels, 0, width, 0, 0, width, height);
     
            for(int x = 0; x < pixels.length; ++x) {
                pixels[x] = (pixels[x] == fromColor) ? targetColor : pixels[x];
            }
         // create result bitmap output 
            Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());
            //set pixels
            result.setPixels(pixels, 0, width, 0, 0, width, height);
     
            return result;
        }
    }
    

    Define from and to color in the colors.xml

    <color name="red">#FB0000</color> 
    <color name="yell">#FFC953</color>
    

    and use the above method as below.

    iv.setImageBitmap(replaceColor(bitmap,getResources().getColor(R.color.red),getResources().getColor(R.color.yell)));