iphone - Core Graphics,如何绘制带有椭圆透明孔的矩形?

标签 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);
}

当我尝试从矩形中删除椭圆时,它不起作用。

有人有解决办法吗?

最佳答案

这超出了我的想象,但是......

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);

您实际上可能需要使用CGContextEOFillPath,但我永远无法keep them straightCGContextClip 类型的函数应该在绘制之前使用,而不是之后使用,但在这种情况下可能没有必要。

也就是说,您不应该在 -drawRect: 实现中执行此操作,但应该在 CAShapeLayer 上设置路径,它是此 View 的子层,或其唯一的层,或者实际上,如果可能的话,可以使用一个层来代替此 View 。

另请注意,传递到 drawRect: 的矩形可能只是整个 View 的一部分,因此您的代码将按原样产生一些非常奇怪的结果。您是指 self.bounds 吗?

关于iphone - Core Graphics,如何绘制带有椭圆透明孔的矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6867300/

相关文章:

iphone - 一起使用 AVCaptureSession 和 AVAudioPlayer

iphone - 找不到 cassert 文件,但我使用 Box2d 模板

ios - 如何从父层绘制多个 CALayer 子层

ios - 是否有快速绘制二维数组的推荐方法?

ios - 在 iOS 应用程序中为动态下载的图像添加样式

iphone - UIWebView链接点击

iphone - 哪种 iPhone 应用广告解决方案的费率最优惠?

objective-c - CGPDFPageRef 到 CGImageRef/NSBitmapImageRep 无需绘制

macos - 这个方法的签名是什么?

ios - 如何验证与 MacRoman 兼容的字符