iOS:UIBezierPath和CAShapeLayer fillRule

我之前使用过UIBezierPathCAShapeLayer 。 但是几乎每次都要用里面的颜色填充path中包含的对象。 但是我希望这个时候能够填充UIBezierPath包含的对象之外的颜色。

我只写了下面的简单代码,试图让我熟悉fillRule属性:

 CAShapeLayer *myLayer = (CAShapeLayer*) self.layer; //size: 320 X 480 UIBezierPath *testPath = [UIBezierPath bezierPathWithOvalInRect:(CGRect){{100, 100}, 100, 100}]; //a simple circle myLayer.fillRule = kCAFillRuleNonZero; // have tried this as well: kCAFillRuleEvenOdd; myLayer.path = testPath.CGPath; myLayer.fillColor = [UIColor whiteColor].CGColor; 

但是颜色仍然填充在里面。 我想知道的是,如何填补path外的颜色? 如果我在这里使用fillRule错误,我想知道是否有其他方法可以实现这一点。 提前致谢。

主要的问题是你不能真正填充形状的外部 ,因为没有通用的方法来定义这意味着什么。 你需要做的是首先在你的形状的“外部”周围绘制一条path,然后将该圆形添加为子path。 你怎么做取决于你想要使用哪个填充规则。 EvenOdd是最简单的:

 CAShapeLayer *myLayer = (CAShapeLayer*) self.layer; UIBezierPath *testPath = [UIBezierPath bezierPathWithRect:self.bounds]; [testPath appendPath:[UIBezierPath bezierPathWithOvalInRect:(CGRect){{100, 100}, 100, 100}]]; myLayer.fillRule = kCAFillRuleEvenOdd; myLayer.path = testPath.CGPath; myLayer.fillColor = [UIColor whiteColor].CGColor; 

非零有点难,因为你必须强制path逆时针这是不是大多数UIBezierPath便利方法的选项:

 CAShapeLayer *myLayer = (CAShapeLayer*) self.layer; UIBezierPath *testPath = [UIBezierPath bezierPathWithRect:self.bounds]; UIBezierPath *counterClockwise = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100) radius:100 startAngle:0 endAngle:M_PI clockwise:NO]; [counterClockwise appendPath:[UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100) radius:100 startAngle:M_PI endAngle:0 clockwise:NO]]; [testPath appendPath:counterClockwise]; myLayer.fillRule = kCAFillRuleNonZero; myLayer.path = testPath.CGPath; myLayer.fillColor = [UIColor redColor].CGColor; 

根据你如何构build你的实际path,它可能不会有任何区别。

如果你还没有看到它, 缠绕规则文件有一些很好的图表,我觉得很有帮助。