Android位图:将透明像素转换为颜色

ccb*_*ney 16 java android image

我有一个Android应用程序,可以将图像作为位图加载并在ImageView中显示.问题是图像看起来具有透明背景; 这会导致图像上的一些黑色文本在黑色背景下消​​失.

如果我将ImageView背景设置为白色,那种工作,但我在图像上得到了丑陋的大边框,它被拉伸以适合父级(实际图像在中间缩放).

所以 - 我想将位图中的透明像素转换为纯色 - 但我无法弄清楚如何做到这一点!

任何帮助将不胜感激!

谢谢克里斯

iag*_*een 29

如果您将图像作为资源包含在内,最简单的方法就是在像gimp这样的程序中自己编辑图像.您可以在那里添加背景,并确保它看起来像什么,并且没有用于处理每次加载时修改图像的功率.

如果您自己无法控制图像,可以通过执行某些操作来修改它,假设您Bitmap已被调用image.

Bitmap imageWithBG = Bitmap.createBitmap(image.getWidth(), image.getHeight(),image.getConfig());  // Create another image the same size
imageWithBG.eraseColor(Color.WHITE);  // set its background to white, or whatever color you want
Canvas canvas = new Canvas(imageWithBG);  // create a canvas to draw on the new image
canvas.drawBitmap(image, 0f, 0f, null); // draw old image on the background
image.recycle();  // clear out old image 
Run Code Online (Sandbox Code Playgroud)


MrZ*_*der 5

您可以遍历每个像素并检查它是否透明.

像这样的东西.(未测试)

        Bitmap b = ...;
        for(int x = 0; x<b.getWidth(); x++){
            for(int y = 0; y<b.getHeight(); y++){
                if(b.getPixel(x, y) == Color.TRANSPARENT){
                    b.setPixel(x, y, Color.WHITE);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

  • 另外,您可以尝试的另一种方法是创建一个纯白色的新位图,然后在白色位图上绘制位图.(这样您就没有边框,也不必迭代整个位图. (3认同)
  • 如果您采用这种策略,请不要使用`getPixel`.每当你遍历"Bitmap"中的每个像素时,你都应该支持[`getPixels`](http://developer.android.com/reference/android/graphics/Bitmap.html#getPixels%28int [],%20int,相反,%20int,%20int,%20int,%20int,%20int%29). (2认同)