我有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;
}
答案 0 :(得分:0)
使用Canvas.drawRoundRect()
和BitmapShader
执行此操作:
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;
}
}