我有一个位图,我需要将它的一些像素设置为透明。虽然我使用 Config.ARGB_8888 创建位图,但当我在其上调用 Bitmap.hasAlpha() 时,它返回 false。我不能使用 Bitmap.setHasAlpha(),因为它只在 API 级别 12 中添加,而我支持的最低 API 需要为 9。我该怎么做?
问问题
1510 次
2 回答
0
// Convert red to transparent in a bitmap
public static Bitmap makeAlpha(Bitmap bit) {
int width = bit.getWidth();
int height = bit.getHeight();
Bitmap myBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int [] allpixels = new int [ myBitmap.getHeight()*myBitmap.getWidth()];
bit.getPixels(allpixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(),myBitmap.getHeight());
myBitmap.setPixels(allpixels, 0, width, 0, 0, width, height);
return myBitmap;
}
上面的代码等价于 setHasAlpha。给它一个位图,它会返回一个 HasAlpha 为真的位图,因此能够具有透明度。这适用于 API 级别 8。我没有在任何更低的级别上测试过它。
于 2014-06-19T18:14:15.140 回答
0
干得好:
Paint paint = new Paint();
paint.setAlpha(100);
canvas.drawBitmap(bitmap, src, dst, paint);
编辑:
//Create an array of pixels of the bitmap using Bitmap getPixels function
//Traverse through the pixels array and if that pixel matches your condition to change it to transparent
// Change the color of that pixel to transparent using Color.Transparent
//Finally set them back using Bitmap setPixels function
示例代码:
import android.graphics.Color;
int[] pixels = new int[myBitmap.getHeight()*myBitmap.getWidth()];
myBitmap.getPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
//traverse through pixel array and if condition is met
pixels[i] = Color.TRANSPARENT;
myBitmap.setPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
于 2013-07-24T19:36:31.117 回答