How to make canvas.drawBitmap transparent?

I am trying to create an animated wallpaper.

Mostly my wallpapers have some background image and some foreground images. I want to share foreground images with different backgrounds.

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(); } 

My foreground image is png, which has a lot of transparent space.

I downloaded the foreground image as follows:

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

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, where it should display a transparent color and thus cover the background with an ugly white rectangle.

I am wondering if anyone has any tips for me to make this transparent. I tried setting options.inPreferredConfig = Bitmap.Config.ARGB_8888; for BitmapFactory, but that didn't help.

+1
source share
2 answers
 Paint paint = new Paint(); paint.setAlpha(70); // you can change number to change the transparency level Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.someDrawable); canvas.drawBitmap(image, x, y, paint); 
0
source

You need to use Paint and set the mixing 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(); } 

See PorterDuff.Mode for various mixing parameters (there are many of them ...)

0
source

Source: https://habr.com/ru/post/1490518/


All Articles