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

3
我正在尝试绘制一个由椭圆形中空的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);
}

当我尝试从矩形中去除椭圆时,它没有起作用。有人有解决方案吗?
1个回答

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

你可能需要使用CGContextEOFillPath,我总是搞混它们。在绘制之前应该使用CGContextClip类型的函数,而不是在绘制之后使用,但在这种情况下它们可能并不是必要的。

话虽如此,你不应该在-drawRect:实现中执行此操作,而是应该将路径设置在此视图的子层CAShapeLayer上,或者只是唯一的图层,或者如果可能的话,使用代替此视图的图层。

同时请注意,传递给drawRect:的矩形可能只是整个视图的一部分,因此您的代码可能会产生一些非常奇怪的结果。您是否意味着self.bounds


谢谢,节省了我的时间 :) - Fahri Azimov
CGMutablePathRef cutoutRect - 如果你想要删除警告。 - LEO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接