使用XferMode在Canvas上绘制圆形位图

时间:2015-08-09 11:27:45

标签: android canvas bitmap xfermode

我正在尝试将圆形位图绘制到画布中。如果我想要绘制的画布是透明的,则位图会被正确剪裁,但如果我之前使用不同的颜色绘制了一个矩形则不会。

enter image description here enter image description here

继承人我得到了什么

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

有人知道如何解决这个问题吗? Thx提前! :)

1 个答案:

答案 0 :(得分:1)

BitmapShader完成了这个伎俩:

        [...]
        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();
        [...]

其他信息:

CircleTranform