Core Graphics, how to draw a Rectangle with an ellipse transparency hole?

此生再无相见时 提交于 2019-11-30 23:25:59

This is off the top of my head, but...

CGPathRef cutoutRect = CGPathCreateMutable();       
CGPathAddRect(cutoutRect, NULL, rect);
CGPathAddEllipseInRect(cutoutRect, NULL, ellipseRect);

CGContextAddPath(context, cutoutRect);  
CGContextSetRGBFillColor(context, 1.0, 1.0, 0.0, 1.0);
CGContextFillPath(context);

You may actually need to use CGContextEOFillPath, I can never keep them straight. The CGContextClip-type functions should be used before drawing rather than after, but they're probably not necessary in this case.

That said, you shouldn't be doing this in a -drawRect: implementation, but the path should be set on a CAShapeLayer which is a sublayer of this view, or its only layer, or, indeed, a layer which is used instead of this view if possible.

Also note that the rectangle passed into drawRect: may be only part of the whole view, so your code will have some pretty weird results as-is. Did you mean self.bounds?

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