ios - 如何创建一个圆形虚线作为 CALayer?

标签 ios objective-c calayer

我读了这篇文章 Draw dotted (not dashed!) line, with IBDesignable in 2017关于绘制虚线(而不是虚线)。但是,我一般不太熟悉图形,我想知道如何使用 CALayer 执行此操作(因此我不必执行整个获取当前图形上下文的操作)。

我正在尝试制作一条看起来像这样的虚线(白色部分,忽略背景):

dotted line

这是我用来生成虚线的代码:

CAShapeLayer *shapelayer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:startPoint];
[path addLineToPoint:endPoint];
[path setLineCapStyle:kCGLineCapRound];
UIColor *fill = [UIColor whiteColor];
shapelayer.strokeStart = 0.0;
shapelayer.strokeColor = fill.CGColor;
shapelayer.lineWidth = 4.0;
shapelayer.lineJoin = kCALineJoinRound;
shapelayer.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:4],[NSNumber numberWithInt:6 ], nil];
shapelayer.path = path.CGPath;

return shapelayer;

如何镜像我引用的 SO 帖子中的代码,但继续使用 CALayer?

我尝试像这样修改该帖子中的代码:

UIBezierPath * path = [[UIBezierPath alloc] init];
[path moveToPoint:startPoint];
[path addLineToPoint:endPoint];
[path setLineWidth:8.0];
CGFloat dashes[] = { path.lineWidth, path.lineWidth * 2 };
[path setLineDash:dashes count:2 phase:0];
[path setLineCapStyle:kCGLineCapRound];
[path stroke];

CAShapeLayer *returnLayer = [CAShapeLayer layer];
returnLayer.path = path.CGPath;
return returnLayer;

然而,这最终什么也没画。

最佳答案

希望对您有所帮助。

CAShapeLayer *circleLayer = [CAShapeLayer layer];
[circleLayer setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 100, 100)] CGPath]];
circleLayer.lineWidth = 2.0;
[circleLayer setStrokeColor:[[UIColor redColor] CGColor]];
[circleLayer setFillColor:[[UIColor clearColor] CGColor]];
circleLayer.lineJoin = kCALineJoinRound;
circleLayer.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber numberWithInt:3 ], nil];
// self.bgImage is parentView
[[self.bgImage layer] addSublayer:circleLayer];

self.bgImage.layer.borderWidth = 1.0f;
self.bgImage.layer.borderColor = [[UIColor blueColor]CGColor];

我附上了图像的输出 enter image description here

关于ios - 如何创建一个圆形虚线作为 CALayer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37972424/

相关文章:

objective-c - Swift 字符串格式与 Objective-C

objective-c - 在 CGContext 中使用比例变换绘制平铺图像会产生精度误差

objective-c - 如何用 Spritekit 实现这个动画?

ios - 我无法让类别出现在表格 View 单元格中

ios - UITableView 添加单元格动画

iphone - 每次在 xcode 中构建 "dependent Project"

ios - 为什么应用 bezierPathWithRoundedRect 蒙版会产生与设置图层的 cornerRadius 不同的结果?

javascript - 强制 iOS iPhone youtube 嵌入播放器退出全屏

iphone - iOS UIAutomation UIAActivityIndi​​cator

swift - CALayer 的属性 isGeometryFlipped 在 macOS 上不起作用