7

我有两个位图,背景前景。如何在不使用另一个 Canvas 的情况下在背景上绘制位图前景?

解决方案:

1) 首先使用附加选项 ARGB_8888 从资源创建位图

BitmapFactory.Options options = new BitmapFactory.Options();  
options.inPreferredConfig = Bitmap.Config.ARGB_8888;

2) 声明位图

Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.background, options);  
Bitmap foreground = BitmapFactory.decodeResource(getResources(), R.drawable.foreground, options);

3) onDraw()函数内部绘制图形

protected void onDraw(Canvas canvas)    
{  
    canvas.drawColor(Color.White);

    Paint paint = new Paint();
    canvas.drawBitmap(background, 0, 0, paint);
    paint.setXfermode( new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
    canvas.drawBitmap(foreground, 0, 0, paint); 
}

正如 Soxxeh 所说,这是非常好的信息来源:http: //developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/Xfermodes.html

4

2 回答 2

5

尝试这个:

canvas.drawBitmap(backgroundImageBitmap, 0.0f, 0.0f, null);
canvas.drawBitmap(foregroundImageBitmap, 0.0f, 0.0f, null);

第二个图像(前景图像)必须具有 Alpha 方面,否则您无法看穿它。

于 2012-06-09T19:22:58.757 回答
1

If you use an ImageView you can set the first bitmap as a background and the second as an image source.

<ImageView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    android:src="@drawable/foreground"/>
于 2012-06-09T19:27:55.873 回答