石英和剪裁区域

时间:2013-08-09 18:40:19

标签: ios drawrect quartz-2d clipping

我对Quartz和裁剪区有疑问:

我想要一个矩形A. 在这个矩形里面我想要一个矩形B. B dveve的填充也切入A:我希望A被B刺穿。在石英中做这个的最佳方法是什么?我真的不明白剪辑是怎样的

2 个答案:

答案 0 :(得分:0)

如果我理解正确,您想在较大的矩形内绘制一个较小的矩形,以便内部矩形是透明的。您可以通过绘制CAShapeLayer来实现此目的,该路径包含两个矩形作为子路径。不要忘记将图层的填充规则设置为kCAFillRuleEvenOdd

尝试这样的事情:

CGRect rectA = CGRectMake(100, 100, 200, 200);
CGRect rectB = CGRectMake(150, 150, 100, 100);

UIBezierPath *path=[[UIBezierPath alloc] init];

// Add sub-path for rectA
[path moveToPoint:CGPointMake(rectA.origin.x, rectA.origin.y)];
[path addLineToPoint:CGPointMake(rectA.origin.x+rectA.size.width, rectA.origin.y)];
[path addLineToPoint:CGPointMake(rectA.origin.x+rectA.size.width, rectA.origin.y+rectA.size.height)];
[path addLineToPoint:CGPointMake(rectA.origin.x, rectA.origin.y+rectA.size.height)];
[path closePath];

// Add sub-path for rectB
[path moveToPoint:CGPointMake(rectB.origin.x, rectB.origin.y)];
[path addLineToPoint:CGPointMake(rectB.origin.x+rectB.size.width, rectB.origin.y)];
[path addLineToPoint:CGPointMake(rectB.origin.x+rectB.size.width, rectB.origin.y+rectB.size.height)];
[path addLineToPoint:CGPointMake(rectB.origin.x, rectB.origin.y+rectB.size.height)];
[path closePath];

// Create CAShapeLayer with this path
CAShapeLayer *pathLayer = [CAShapeLayer layer];
[pathLayer setFillRule:kCAFillRuleEvenOdd]; /* <- IMPORTANT! */
[pathLayer setPath:path.CGPath];
[pathLayer setFillColor:[UIColor blackColor].CGColor];

// Add the CAShapeLayer to a view
[someView.layer addSublayer:pathLayer];

答案 1 :(得分:0)

我用这个简单的方法解决了:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 0);
    CGContextFillRect(context,self.bounds);
    CGContextAddRect(context, self.bounds);
    //Add cropped rectangle:
    CGContextAddRect(context, _croppedRegion);
    //Clip:
    CGContextEOClip(context);
    CGContextSetRGBFillColor(context, 255.0, 255.0, 255.0, 0.5);
    CGContextFillRect(context, self.bounds);
}