问题描述
我有一个Android应用程序到另一个图像显示的图像,使得第二图像的白色是透明的。要做到这一点,我已经用了两个的ImageView
S,与原始图像进行叠加为 bitmap1
和图像是透明的 bitmap2
。当我运行它,我得到一些例外的 setPixel
方法。
I have an Android application to display an image on another image, such that second image's white colour is transparent. To do this, I have used two ImageView
s, with the original image to be overlaid as bitmap1
and the image to be made transparent as bitmap2
. When I run this, I get some exceptions at the setPixel
method.
下面是我的code:
Bitmap bitmap2 = null;
int width = imViewOverLay.getWidth();
int height = imViewOverLay.getHeight();
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
if(bitMap1.getPixel(x, y) == Color.WHITE)
{
bitmap2.setPixel(x, y, Color.TRANSPARENT);
}
else
{
bitmap2.setPixel(x, y, bitMap1.getPixel(x, y));
}
}
}
imViewOverLay
是 ImageView的重叠图像的
。任何想法可能什么错在上面code?
imViewOverLay
is the ImageView
of the overlay image. Any idea what might be going wrong in the above code?
推荐答案
我认为你需要使它可变加载资源,以一个可变的位图
i think you need to make it mutableLoading a resource to a mutable bitmap
我这样做
BitmapFactory.Options bitopt=new BitmapFactory.Options();
bitopt.inMutable=true;
mSnareBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.snare, bitopt);
另外,我发现我需要设置阿尔法的东西低于255为它呈现透明背景的图像。
also, i found i needed to set alpha to something less than 255 for it to render the image with transparent background.
mPaint.setAlpha(250);
canvas.drawBitmap(mSnareBitmap, 0, 30, mPaint);
顺便说一句,用白色作为你的透明色是不是一个好主意,因为你会得到你的不透明物体的边缘锯齿问题。我用绿色的,因为我的叠加图像没有任何绿色的(像电影绿屏),那么我可以根据绿色值的倒数删除循环内的绿化,并设置alpha值。
by the way, using white as your transparent color isn't a great idea because you will get aliasing problems at the edges of your opaque objects. i use green because my overlay images don't have any green in (like a green screen in the movies) then i can remove the green inside the loop and set the alpha value based on the inverse of the green value.
private void loadBitmapAndSetAlpha(int evtype, int id) {
BitmapFactory.Options bitopt=new BitmapFactory.Options();
bitopt.inMutable=true;
mOverlayBitmap[evtype] = BitmapFactory.decodeResource(getResources(), id, bitopt);
Bitmap bm = mOverlayBitmap[evtype];
int width = bm.getWidth();
int height = bm.getHeight();
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
int argb = bm.getPixel(x, y);
int green = (argb&0x0000ff00)>>8;
if(green>0)
{
int a = green;
a = (~green)&0xff;
argb &= 0x000000ff; // save only blue
argb |= a; // put alpha back in
bm.setPixel(x, y, argb);
}
}
}
}
这篇关于位图透明的,使得特定的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!