I wrote a view layout with transparent shapes earlier, but there are drawbacks to all of them. Here’s a powerful, defect-free approach.

I don’t know what the current minSdkVersion of your project is, but mine has always been 14, and recently it has changed to 16. My project has a wide range of adaptation.

I don’t agree with that. The minimum API requirement is 19. Mine is 14 or 16, what if I want to match api19 below?

After my research, the following can be perfectly adapted to my API requirements. I haven’t seen anything like this online yet, at least I haven’t.

Good words not to say, look at the following code, interested students can press the following method to try their own.

Suitable for all shapes, not just circles

Define brush

val mViewPaint = Paint()
mViewPaint.isAntiAlias = true
mViewPaint.style = Paint.Style.FILL
Copy the code

Draw with path

The rest is filled, leaving a circular area

Val path = path () path.moveto (0F, 0F)// The starting point of the current view, Top left path.lineto (width.tofloat (), 0F)// Top right of current view path.lineto (width.tofloat (), Height.tofloat ())// Path.lineto (0F, height.tofloat ())// Path.addCircle (x.toloat (), y.toloat (), Radius.tofloat (), path.direction.ccw // this is important)// Add the shape you want to draw and the area canvas? .drawPath(path, mViewPaint)Copy the code

or

path.addCircle( x.toFloat(), y.toFloat(), radius.toFloat(), Path. The Direction. The CW / / / / this is very important oh) plus you're drawing Path. The shape and area fillType = Path. FillType. The WINDING Path. ToggleInverseFillType () / / reverse filling canvas? .drawPath(path, mViewPaint)Copy the code

Fill the rest, leaving the rounded rectangle area

val rectF = RectF(0F, 0F, width.toFloat(), height.toFloat()) val path = Path() path.moveTo(0F, 0F) path.lineTo(width.toFloat(), 0F) path.lineTo(width.toFloat(), height.toFloat()) path.lineTo(0F, height.toFloat()) path.addRoundRect(rectF, mCornersX, mCornersY, Path.Direction.CCW) canvas? .drawPath(path, mViewPaint)Copy the code

or

Path.addroundrect (rectF, mCornersX, mCornersY, path.direction.cw) path.fillType = path.filltype.WINDING In the mobile phone screen to open the graphics will change path. ToggleInverseFillType () / / reverse fill the canvas? .drawPath(path, mViewPaint)Copy the code

So far, I have not found any problems in the test. There are not many testing machines here. If you find any problems, please send a comment to me.