核心图形,如何用椭圆透明孔绘制一个矩形?

Jan*_*Jan 3 iphone core-graphics quartz-graphics

我正在尝试绘制一个椭圆形挖空的320x480矩形.想象一下,在矩形上绘制一个填充的矩形,一个填充的椭圆,然后从矩形中移除椭圆,留下一个透明孔.

- (void)drawRect:(CGRect)rect
{
        // Drawing code.
    CGContextRef context = UIGraphicsGetCurrentContext();
    // Set color to red
    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
    // Add rectange
    CGContextAddRect(context, rect);
    // Fill rectange
    CGContextFillRect(context, rect);

    // Create a elipse to be removed from rectange

    CGPathRef circlePath = CGPathCreateMutable();       
    CGPathAddEllipseInRect(circlePath , NULL , elipseRect);

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

    // clip elipse... (DO NOT WORK)
    CGContextEOClip(context);
}
Run Code Online (Sandbox Code Playgroud)

当我试图从矩形中移除椭圆时,它不起作用.

有人有解决方案吗?

Joe*_*orn 13

这不是我的头脑,但......

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);
Run Code Online (Sandbox Code Playgroud)

你实际上可能需要使用CGContextEOFillPath,我永远不能保持它们.该CGContextClip型功能应使用绘制,而不是之后,但他们可能没有必要在这种情况下.

也就是说,你不应该在一个-drawRect:实现中这样做,但路径应该设置在CAShapeLayer这个视图的子层,或者它唯一的层,或者实际上是一个层,如果可能的话,用它代替这个视图.

另请注意,传入的矩形drawRect:可能只是整个视图的一部分,因此您的代码将会有一些非常奇怪的结果.你的意思是self.bounds