Android - 剪切圆圈并从现有的位图创建单独的位图

时间:2014-07-01 14:59:04

标签: android image bitmap android-canvas ondraw

我有onDraw方法,我希望剪切一小块大bitmap。这将是一个圆圈(位置X和Y)。然后我想通过canvas绘制它。

我因为这个原因重写了method from this answer,但总是得到灰色圆圈而不是圆圈的大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

1 个答案:

答案 0 :(得分:0)

使用Canvas.drawRoundRect()BitmapShader执行此操作:

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

}