【问题标题】:iOS: UIBezierPath and CAShapeLayer fillRuleiOS:UIBezierPath 和 CAShapeLayer fillRule
【发布时间】:2013-10-15 18:06:29
【问题描述】:

我之前使用过UIBezierPathCAShapeLayer。但几乎每次都与填充路径中包含的对象一起使用内部颜色。但是这次我想填充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;

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

【问题讨论】:

    标签: ios uibezierpath cashapelayer


    【解决方案1】:

    主要问题是您无法真正填充形状的外部,因为没有通用的方法来定义其含义。您需要做的是首先在形状的“外部”周围绘制一条路径,然后将圆圈添加为子路径。你如何做到这一点取决于你想使用哪个填充规则。 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;
    

    NonZero 有点困难,因为您必须强制路径为逆时针方向,这对于大多数 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;
    

    根据您构建实际路径的方式,这两种方式都可能没有什么不同。

    如果您还没有看过,winding rules documentation 有一些我觉得很有帮助的漂亮图表。

    【讨论】:

    • 嗨,嘿,你真的很擅长这个。 +1。谢谢。为了完整起见,CGMutablePaths 是否可以实现同样的事情?提前致谢。
    • 不过,我会先将此标记为答案。希望你能用这个详细说明CGMutablePaths。
    • 是的,同样的基本思想适用于CGPaths,使用CGPathAddArc等。
    • 谢谢,如果您不介意,您能否在上面的答案中提供一些带有CGPath 的代码示例?如果不是太麻烦的话。提前致谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多