Masking a Drawable/Bitmap on Android

后端 未结 5 1626
挽巷
挽巷 2020-12-28 17:12

I\'m currently looking for a way to use a black and white bitmap to mask the alpha channel of another bitmap or Drawable on Android. I\'m curious as to what the best way to

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-28 17:58

    I got it working, so it's something like this

        // we first same the layer, rectF is the area of interest we plan on drawing
        // this will create an offscreen bitmap
        canvas.saveLayer(rectF, null, Canvas.MATRIX_SAVE_FLAG
                | Canvas.CLIP_SAVE_FLAG | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG
                | Canvas.FULL_COLOR_LAYER_SAVE_FLAG
                | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
    
        // draw our unmasked stuff
        super.draw(canvas);
        // We same a layer again but this time we pass a paint object to mask
        // the above layer
        maskPaint = new Paint()
        maskPaint.setColor(0xFFFFFFFF);
        maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
    
        canvas.saveLayer(rectF, maskPaint,
                Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG
                        | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG
                        | Canvas.FULL_COLOR_LAYER_SAVE_FLAG
                        | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
        // we draw the mask which is black and white. In my case
        // I have a path, and I use a blurPaint which blurs the mask slightly
        // You can do anti aliasing or whatever you which. Just black & white
        canvas.drawPath(path, blurPaint);
        // We restore twice, this merges the results upward
        // as each saveLayer() allocates a new drawing bitmap
        canvas.restore();
        canvas.restore();
    

提交回复
热议问题