Drawing “holes” in a canvas

大憨熊 提交于 2019-12-09 09:30:42

问题


I'm trying to draw a shape like this in the onDraw method of a custom view.

Unfortunately, I cannot "cut" the transparent circle on the canvas, (by drawing a circle with a Color.Transparent).

Should I first draw the shape in another bitmap then draw it on the canvas provided by onDraw ? Or is it a better (simpler) way to do this ?

Here is the code I tried (works with Color.WHITE) :

mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.TRANSPARENT);
mPaint.setStrokeWidth(4);
mPaint.setStyle(Style.STROKE);

canvas.drawColor(getResources().getColor(R.color.black_overlay));
canvas.drawCircle(-3*(this.getBottom()-this.getTop())/4, (this.getTop()+this.getBottom())/2, this.getBottom()-this.getTop(), mPaint);

PS : I got the exact shape I wanted while using Color.WHITE :

Solution

@Override
public void onDraw(Canvas canvas)
{
    mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);
    mCanvas.drawColor(getResources().getColor(R.color.black_overlay));
    mCanvas.drawCircle(-3*(getHeight())/4, (getHeight())/2, getHeight(), mPaint);
    canvas.drawBitmap(mBitmap, 0, 0, null);
}
with
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPaint.setStrokeWidth(4);
    mPaint.setStyle(Style.STROKE);
    mPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));

Note : the createBitamp and the new canvas should be moved out of the onDraw Method.

来源:https://stackoverflow.com/questions/18130341/drawing-holes-in-a-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!