如果您只想用另一张图像的相应 x,y 像素替换透明的 x,y 像素,您可以执行以下操作。第一个参数是您的透明图像位图,第二个参数是另一个图像位图,第三个参数是一个布尔标志,仅用于替换透明区域的像素。当然,您需要两个图像具有相同的宽度和高度,才能从另一张图像中获取正确的对应 x,y 像素值。
public static void combineBitmaps(Bitmap transBitmap, Bitmap otherBitmap, boolean replaceTransparentAreaOnly){
try
{
Bitmap outputBitmap = Bitmap.createBitmap(transBitmap.getWidth(), transBitmap.getHeight(), Bitmap.Config.ARGB_8888);
for (int x = 0; x < transBitmap.getWidth(); x++) {
for (int y = 0; y < transBitmap.getHeight(); y++) {
int rgba = transBitmap.getPixel(x, y);
int red = Color.red(rgba);
int blue = Color.blue(rgba);
int green = Color.green(rgba);
int alpha = Color.alpha(rgba);
//replace only transparent area
if(replaceTransparentAreaOnly)
{
//transparent pixel found, replace it with the corresponding x,y pixel of the other image
if (rgba == Color.TRANSPARENT) {
outputBitmap.setPixel(x, y, otherBitmap.getPixel(x, y));
}
//otherwise set x,y pixel based on transparent image RGB colour
else {
outputBitmap.setPixel(x, y, Color.rgb(red, green, blue));
}
}
//replace non-transparent area
else
{
//non-transparent pixel found, replace it with the corresponding x,y pixel of the other image
if (rgba != Color.TRANSPARENT) {
outputBitmap.setPixel(x, y, otherBitmap.getPixel(x, y));
}
//otherwise set x,y pixel based on transparent image RGB colour
else {
outputBitmap.setPixel(x, y, rgba);
}
}
}
}
//save the new outputBitmap here
}catch (Exception e){
}
}
你可以像下面这样调用这个辅助函数:
Bitmap appleBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.apple);
Bitmap androidBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.other_image);
combineBitmaps(appleBitmap, androidBitmap, true);
将Apple图像的仅透明区域替换为另一个(Android图像)后的结果如下:
如果您想替换苹果图像的非透明区域(白色像素),结果将如下所示: