使用canvas.drawImageRect绘制带透明的白色图片,如何为其着色?
哦,这个问题我之前踩过坑!默认情况下用drawImageRect的时候,Paint的setColor()确实不会直接给带透明通道的白色图片染色——因为它默认是直接绘制图片的原始像素,不会把Paint颜色和图片像素做混合。不过有几个非常实用的方法能解决这个需求,我给你详细说说:
方法1:使用PorterDuffColorFilter(最推荐,简单高效)
这是最直接的方案,利用PorterDuff的混合模式,让Paint的颜色只填充图片的透明通道区域,完美适配你的场景。
代码示例:
Paint tintPaint = new Paint(); // 用SRC_IN模式:只保留原图片的Alpha通道区域,填充Paint设置的颜色 tintPaint.setColorFilter(new PorterDuffColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_IN)); // 绘制时传入这个Paint canvas.drawImageRect(yourTransparentWhiteImage, srcRect, dstRect, tintPaint);
原理很简单:SRC_IN模式会让图片的透明区域保持透明,非透明区域完全替换成你设置的黄色,正好对应你那张带透明的白色图片——白色部分会被彻底换成黄色,透明部分不受影响。
方法2:使用ColorMatrixColorFilter(适合灵活调整颜色)
如果你后续需要更复杂的颜色调整(比如调亮度、饱和度,或者叠加多种颜色),可以用颜色矩阵来实现:
ColorMatrix colorMatrix = new ColorMatrix(); // 先把图片转成灰度(去掉原有白色的颜色信息) colorMatrix.setSaturation(0); // 定义黄色的颜色矩阵:红、绿拉满,蓝色设为0,保留原Alpha float[] yellowTintArray = { 1, 0, 0, 0, 255, // 红色通道,最后一位是黄色的红分量 0, 1, 0, 0, 255, // 绿色通道,最后一位是黄色的绿分量 0, 0, 1, 0, 0, // 蓝色通道,最后一位是黄色的蓝分量 0, 0, 0, 1, 0 // Alpha通道保持不变 }; colorMatrix.postConcat(new ColorMatrix(yellowTintArray)); Paint tintPaint = new Paint(); tintPaint.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); canvas.drawImageRect(yourTransparentWhiteImage, srcRect, dstRect, tintPaint);
这个方法的好处是可以灵活调整颜色参数,比如想改成橙色,只需要调整数组里的颜色分量就行。
方法3:直接修改Bitmap像素(适合静态图片)
如果你的图片是静态的,不需要动态切换颜色,也可以直接修改Bitmap的像素值:
// 先把原图转成可修改的Bitmap Bitmap mutableBitmap = yourTransparentWhiteImage.copy(Bitmap.Config.ARGB_8888, true); int width = mutableBitmap.getWidth(); int height = mutableBitmap.getHeight(); // 遍历每个像素,替换非透明区域为黄色 for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int pixel = mutableBitmap.getPixel(x, y); int alpha = Color.alpha(pixel); if (alpha > 0) { // 保留原Alpha,替换颜色为黄色 mutableBitmap.setPixel(x, y, Color.argb(alpha, 255, 255, 0)); } } } // 绘制修改后的Bitmap canvas.drawImageRect(mutableBitmap, srcRect, dstRect, null);
不过这个方法要注意性能,大图遍历会比较耗时,所以优先推荐前两种ColorFilter的方案。
总的来说,PorterDuffColorFilter是最适合你当前需求的,代码少、效率高,一步到位就能把带透明的白色图片染成黄色~
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

