如何使canvas.drawBitmap透明? [英] How to make canvas.drawBitmap transparent?

查看:347
本文介绍了如何使canvas.drawBitmap透明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作动画墙纸.

I am trying to create an animated wallpaper.

基本上,我的墙纸有一些背景图片和一些前景图片. 我想在背景不同的前景图片之间交换.

Basically my wallpaper has some background picture, and several foreground pictures. I want to swap between the foreground pictures with different backgrounds.

我有一个如下所示的Draw方法:

I have a Draw method that looks like this:

 protected void onDraw(Canvas canvas){
        super.onDraw(canvas);
        canvas.drawColor(0);
        canvas.drawBitmap(background,0,0,null);

        canvas.drawBitmap(foreground,x,y,null);
        canvas.save();

}

我的前景图片是具有大量透明空间的png.

My foreground picture is a png that has lots of transparent space.

我像这样在前景图片中加载

I loaded in my foreground picture like this:

 foreground=decodeSampledBitmapFromResource(getResources(), R.drawable.c1, 440,320);

此处是从本教程中获得的decodeSampledBitmapFromResource方法的地方: https://developer.android.com/training/displaying-bitmaps/load-bitmap.html

Where the decodeSampledBitmapFromResource method was taken from the tutorial here: https://developer.android.com/training/displaying-bitmaps/load-bitmap.html

我的问题是前景将显示为白色,而前景应显示为透明,从而用难看的白色矩形覆盖背景.

My problem is that the foreground will display white color where it should display transparent color and thus covering the background with an ugly white rectangle.

我想知道是否有人对我有任何建议可以使其透明化. 我试过设置options.inPreferredConfig = Bitmap.Config.ARGB_8888;用于BitmapFactory,但无济于事.

I'm wondering if anyone have any advice for me to make this transparent. I've tried setting options.inPreferredConfig = Bitmap.Config.ARGB_8888; for the BitmapFactory, but it didn't help.

推荐答案

您需要使用Paint并将混合模式设置为SRC_OVER

You need to use Paint and set the mix mode to SRC_OVER

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint paint = new Paint();
    canvas.drawColor(0);
    canvas.drawBitmap(background,srcRect,dstRect,paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
    canvas.drawBitmap(foreground,srcRect2,dstRect2,paint);
    canvas.save();
}

有关各种混合选项,请参见 PorterDuff.Mode (有很多...)

See PorterDuff.Mode for the various mixing options (there are many...)

这篇关于如何使canvas.drawBitmap透明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆