【问题标题】:Core Graphics, how to draw a Rectangle with an ellipse transparency hole?Core Graphics,如何绘制带有椭圆透明孔的矩形?
【发布时间】:2011-07-29 00:14:43
【问题描述】:

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

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

有人有解决办法吗?

【问题讨论】:

    标签: iphone core-graphics quartz-graphics


    【解决方案1】:

    这不是我的想法,但是...

    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-type 函数应该在之前绘制而不是之后使用,但在这种情况下它们可能不是必需的。

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

    还要注意,传递给drawRect: 的矩形可能只是整个视图的一部分,因此您的代码会产生一些非常奇怪的结果。你是说self.bounds吗?

    【讨论】:

    • 谢谢,节省了我的时间:)
    • CGMutablePathRef cutoutRect - 如果你想删除警告。
    猜你喜欢
    • 2011-02-19
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多