androidcanvasbitmapxfermode

Draw Circular Bitmap on Canvas with XferMode


I'am trying to draw a circular bitmap into a canvas. The bitmap gets clipped correctly if the canvas i want to draw on is transparent, but not if i have drawn a rectangle before with a different color.

enter image description here enter image description here

Heres what i got

    paint.setColor(col.colors_Form[1]);
    mCanvas.drawRect(0, 0, dim.titleContainer_Width, dim.titleContainer_Height, paint);

   [...]


    if (!mFormValues_BasicInformation.get(0).getAvatarImage().equals(""))  {

        mCanvas.save();

        mCanvas.translate(300, 300);

        byte[] byteArray = mFormValues_BasicInformation.get(0).getAvatarImage();

        Bitmap bmp = Bitmap.createScaledBitmap(BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length), 250, 250, false);

        final int color = col.colors_Form[1];
        final Paint avatarPaint = new Paint();
        final Rect rect = new Rect(0, 0, bmp.getWidth(),
                bmp.getHeight());

        avatarPaint.setAntiAlias(true);
        mCanvas.drawARGB(0, 0, 0, 0);

        avatarPaint.setColor(color);
        mCanvas.drawCircle(bmp.getWidth() / 2,
                bmp.getHeight() / 2, bmp.getWidth() / 2, paint);
        avatarPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        mCanvas.drawBitmap(bmp, rect, rect, avatarPaint);
        bmp.recycle();

        mCanvas.restore();
    }

Does anybody know how to fix that? Thx in advance! :)


Solution

  • BitmapShader did the trick:

            [...]
            byte[] byteArray = mFormValues_BasicInformation.get(0).getAvatarImage();
            Bitmap bmp = Bitmap.createScaledBitmap(BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length), 500, 500, false);
    
            final Paint avatarPaint = new Paint();
    
            BitmapShader shader = new BitmapShader(bmp, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
            avatarPaint.setShader(shader);
            avatarPaint.setAntiAlias(true);
    
            float r = Math.min(bmp.getWidth(), bmp.getHeight()) / 2f;
            mCanvas.drawCircle(r, r, r, avatarPaint);
    
            bmp.recycle();
            [...]
    

    Additional Information:

    CircleTranform