是否可以在UIBezierPath的可见部分周围绘制路径?
这是我的问题的一个例子
这就是我想要完成的事情
这是我到目前为止所得到的:
- (void)drawRect:(CGRect)rect {
CGFloat side = MIN(rect.size.width, rect.size.height);
CGPoint center = CGPointMake(rect.size.width / 2.0f, rect.size.height / 2.0f);
UIColor *yinYangColor = [UIColor whiteColor];
UIBezierPath *yinYangPath = [UIBezierPath bezierPath];
// Draw Yin&Yang part
[yinYangPath addArcWithCenter:CGPointMake(center.x, center.y - side / 4.0f) radius:side / 4.0f startAngle:M_PI_2 endAngle:-M_PI_2 clockwise:YES];
[yinYangPath addArcWithCenter:CGPointMake(center.x, center.y + side / 4.0f) radius:side / 4.0f startAngle:M_PI_2 endAngle:-M_PI_2 clockwise:NO];
[yinYangPath addArcWithCenter:CGPointMake(center.x, center.y) radius:side / 2.0f startAngle:-M_PI_2 endAngle:M_PI_2 clockwise:YES];
[yinYangPath closePath];
[yinYangColor setFill];
[yinYangPath fill];
// Add border
CAShapeLayer *borderLayer = [[CAShapeLayer alloc] init];
borderLayer.path = yinYangPath.CGPath;
borderLayer.fillColor = [UIColor clearColor].CGColor;
borderLayer.strokeColor = [UIColor blackColor].CGColor;
borderLayer.lineWidth = 5.0f;
[self.layer addSublayer:borderLayer];
}
答案 0 :(得分:3)
角度π/ 2弧度沿正y轴。
在标准UIKit几何体中,正y轴指向屏幕底部。因此,顶弧(center.y - side/4
)需要以角度-π/ 2开始并以角度π/ 2结束。由于你得到了这些,你的第二个弧不会从第一个弧结束的地方开始,所以你的路径包含一条连接这些点的直线。同样适用于你的第二和第三弧。图像中可见的单条直线实际上是这两条线的组合。
另外,顺便提一下,传递给rect
的{{1}}理论上不一定是视图的界限。最好不要这样对待它。
另外,您不应在drawRect:
中添加子图层。您应该在drawRect:
或init
中执行此操作,并确保不要复制图层。我想也许你正在使用layoutSubviews
,因为你不希望边界被切断。我会通过边界宽度插入视图边界来解决这个问题:
CAShapeLayer
结果:
如果您希望底部尖端更尖,我会通过将所有绘图剪切到路径,然后将边框绘制两倍厚度来实现。边界的一半将被拉出路径并被剪掉,留下一个尖锐的点。在这种情况下,您不必插入边界。
- (void)drawRect:(CGRect)dirtyRect {
CGFloat lineWidth = 4;
CGRect rect = CGRectInset(self.bounds, lineWidth / 2, lineWidth / 2);
CGFloat side = MIN(rect.size.width, rect.size.height);
CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
UIBezierPath *path = [UIBezierPath bezierPath];
CGFloat smallRadius = side / 4;
[path addArcWithCenter:CGPointMake(center.x, center.y - smallRadius) radius:smallRadius startAngle:-M_PI_2 endAngle:M_PI_2 clockwise:NO];
[path addArcWithCenter:CGPointMake(center.x, center.y + smallRadius) radius:smallRadius startAngle:-M_PI_2 endAngle:M_PI_2 clockwise:YES];
[path addArcWithCenter:center radius:side / 2 startAngle:M_PI_2 endAngle:-M_PI_2 clockwise:NO];
[path closePath];
[path setLineJoinStyle:kCGLineJoinRound];
[path setLineWidth:lineWidth];
[[UIColor whiteColor] setFill];
[path fill];
[[UIColor blackColor] setStroke];
[path stroke];
}