更改位图颜色

时间:2021-02-28 16:55:45

标签: android colors bitmap colormatrix porter-duff

有一个白色背景的位图,里面有一个橙色的三角形。我想要做的是将橙色三角形的颜色更改为我想要的颜色,我该如何用代码做到这一点?我使用了 Porterduff 和 Color Matrix,但没有得到我想要的结果。

原文:click to see the picture

我想用代码做什么:click to see the picture

我不想改变白色背景颜色。

1 个答案:

答案 0 :(得分:0)

我已使用此方法更改位图运行时的颜色。试试看。

 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;
    }
}

在colors.xml中定义from和to颜色

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

并使用上述方法如下。

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