0

I have onDraw method where I want to cut a small piece of large bitmap. This will be a circle (position X and Y). Then I want to draw it by canvas.

I rewrite method from this answer for that reason, but always got grey circle instead circle piece of large Bitmap.

private Bitmap cutCircleBitmap() {
        Bitmap output = Bitmap.createBitmap(2 * RADIUS, 2 * RADIUS, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(bitmapX - RADIUS, bitmapY - RADIUS, 2 * RADIUS, 2 * RADIUS);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawCircle(RADIUS, RADIUS, RADIUS, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

enter image description here

Community
  • 1
  • 1
Val
  • 4,225
  • 8
  • 36
  • 55

1 Answers1

0

Use Canvas.drawRoundRect() and BitmapShader to do it :

runtime screenshot

public class CropView extends View {
    public CropView(Context context) {
        this(context, null);
    }

    public CropView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CropView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setFilterBitmap(true);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(radius * 2, radius * 2);
    }

    private Paint mPaint;
    private int radius = 100;

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.BLACK);  // draw background help us see the result
        Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample);
        canvas.drawBitmap(cropCircleBitmap(srcBitmap, 200, 60), 0, 0, mPaint);
    }

    private Bitmap cropCircleBitmap(Bitmap srcBitmap, float left, float top) {
        Bitmap dstBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(dstBitmap);

        canvas.drawBitmap(srcBitmap, -left, -top, mPaint);

        mPaint.setShader(new BitmapShader(dstBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));

        dstBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        canvas.setBitmap(dstBitmap);

        canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), radius, radius, mPaint);

        return dstBitmap;
    }

}
VinceStyling
  • 3,707
  • 3
  • 29
  • 44