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

后端 未结 1 1212
失恋的感觉
失恋的感觉 2021-01-06 15:24

I am trying to draw a 320x480 rectangle that is hollowed by a ellipse. Imagine drawing a filled rectangle, over the rectangle an filled ellipse, and remove the ellipse from

相关标签:
1条回答
  • 2021-01-06 15:56

    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?

    0 讨论(0)
提交回复
热议问题