How to remove (make transparent) one user region on an Android canvas?

I override Android ImageView to make the corners of my image transparent. I can do this cropping the canvas in my onDraw (canvas canvas):

@Override protected void onDraw(Canvas canvas) { Path clipPath = new Path(); int w = this.getWidth(); int h = this.getHeight(); clipPath.addRoundRect(new RectF(0,0,w,h), 10.0f, 10.0f, Path.Direction.CW); canvas.clipPath(clipPath); super.onDraw(canvas); } 

Unfortunately, it is not possible to smooth this round rectangle, and the result is ugly corners:

enter image description here

I know that I can clear parts of my canvas with anti-aliasing using Paint and PorterDuff.Mode.CLEAR , which I don’t know is to specify the round corners as the area to be erased. I am looking for something like this:

 @Override protected void onDraw(Canvas canvas) { //superclass will draw the bitmap accordingly super.onDraw(canvas); final Paint paint = new Paint(); paint.setAntiAlias(true); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); //this will erase a round rectangle, I need the exact inverse canvas.drawRoundRect(rect, rx, ry, paint); } 

Is there a way to "erase" not a round rectangle, but rather, that is, round corners? But what if I just want to erase one of the corners?

+4
source share
1 answer

Drawing with BitmapShader with transparent color for your Paint object.
If you just want to remove one of the corners, try using it as a path instead of RoundRect.

 protected void onDraw(Canvas canvas) { BitmapShader bitmapShader = new BitmapShader(<original drawable>, TileMode.CLAMP, TileMode.CLAMP); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(0xFF000000); paint.setShader(bitmapShader); canvas.drawRoundRect(rect, rx, ry, paint); } 
+4
source

Source: https://habr.com/ru/post/1396412/


All Articles