10

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 ?

Custom shape

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 : Result achieved with 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.

Tryum
  • 660
  • 7
  • 22
  • well, use image if you see that manually is too complicated – Maxim Shoustin Aug 08 '13 at 15:48
  • What is ColorTransparent? Why not post some code of what you tried? See if this helps - http://stackoverflow.com/questions/9988671/android-r-color-transparent-not-fully-transparent – Sundeep Aug 08 '13 at 15:50
  • Color.TRANSPARENT is an android constant. – Tryum Aug 08 '13 at 16:00
  • Is there a view behind that view that could prevent you from seeing the transparent change? (i.e. same color in the background under the new circle?) – haventchecked Aug 08 '13 at 16:03
  • Nope, if I don't call drawColor on the canvas, everything the whole view is transparent. – Tryum Aug 08 '13 at 16:05
  • Here are some questions which may be relevant to your situation: https://stackoverflow.com/questions/14197823/draw-path-with-hole-android https://stackoverflow.com/questions/15841719/android-canvas-draw-a-hole https://stackoverflow.com/questions/13528550/punch-a-hole-in-a-rectangle-overlay-with-hw-acceleration-enabled-on-view http://www.mail-archive.com/android-developers@googlegroups.com/msg232764.html – TN888 Aug 08 '13 at 16:08

0 Answers0