我正在尝试绘制一个被椭圆挖空的 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 straight 。 CGContextClip
类型的函数应该在绘制之前使用,而不是之后使用,但在这种情况下可能没有必要。
也就是说,您不应该在 -drawRect:
实现中执行此操作,但应该在 CAShapeLayer
上设置路径,它是此 View 的子层,或其唯一的层,或者实际上,如果可能的话,可以使用一个层来代替此 View 。
另请注意,传递到 drawRect:
的矩形可能只是整个 View 的一部分,因此您的代码将按原样产生一些非常奇怪的结果。您是指 self.bounds
吗?
关于iphone - Core Graphics,如何绘制带有椭圆透明孔的矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6867300/