我有一个Bitmap,我需要将其部分像素设置为透明。虽然我用Config.ARGB_8888创建了Bitmap,但当我在其上调用Bitmap.hasAlpha()时,它返回false。我不能使用Bitmap.setHasAlpha(),因为它仅在API级别12中添加,而我的最低支持API需要为9.我该怎么做?
答案 0 :(得分:0)
你走了:
Paint paint = new Paint();
paint.setAlpha(100);
canvas.drawBitmap(bitmap, src, dst, paint);
How to change a bitmap's opacity?
编辑:
//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());
答案 1 :(得分: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.我没有在低级别测试它。