swift - 如何绘制两条没有连接线的圆弧路径?

标签 swift core-graphics cgpath

我正在使用 CGMutablePath 绘制一个 wifi 标志。当我通过addArc(center:radius:startAngle:endAngle:clockwise:transform:)绘制第二个圆弧时,它会自动像文档指定的那样绘制一条线如果路径已经包含子路径, 此方法添加一条连接当前点和圆弧起点的线。。没有这条线我怎么画?谢谢

最佳答案

如果你想绘制一条没有从前一点开始的直线的圆弧,你需要在添加圆弧之前将路径移动到圆弧的起点——使用move(to:)。弧的起点可以计算为:

center.x + radius * cos(startAngle)
center.y + radius * sin(startAngle)

您可以利用 CGPath 的功能来创建笔画副本,而不是自己计算点来创建每条弧线的轮廓。这样做,您只需要为图标的每个“栏”创建一个弧形的基本路径:

let basePath = CGMutablePath()

let center     = CGPoint.zero
let startAngle = CGFloat.pi * 0.75 // 135 degrees
let endAngle   = CGFloat.pi * 0.25 //  45 degrees

let radii: [CGFloat] = [10, 20, 30, 40]

for radius in radii {
    // Move to the start point of the arc
    basePath.move(to: CGPoint(x: center.x + radius * cos(startAngle),
                              y: center.y + radius * sin(startAngle)))
    // Add the arc, starting at that same point
    basePath.addArc(center: center, radius: radius,
                    startAngle: startAngle, endAngle: endAngle,
                    clockwise: true)
}

这将创建一个像这样的基本形状,没有任何厚度:

Base path

接下来,您通过抚摸创建基本路径的副本。您可以在此处配置图标条的粗细及其末端的样式(方形或圆形):

let stroked = basePath.copy(strokingWithWidth: 5, // The width/thickness of each stroked arc
                            lineCap: .square,     // Make square corners for the ends of each arc
                            lineJoin: .miter, miterLimit: 0)

结果是这样的形状:

Stroked path

关于swift - 如何绘制两条没有连接线的圆弧路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51040407/

相关文章:

macos - NSRect 与 CGRect : y-axis inversion

objective-c - 像 iBook 一样在 iOS 中加载自动分页的 pdf

swift - 如何为 CGpath 数组的绘制设置动画?

swift - 无法推断通用参数 'FalseContent'

iOS - Crashlytics - 缺少几次崩溃

ios - 再次编辑时 Core Graphics 结果图像不起作用

ios - 查找触摸在路径上的位置(按百分比)

iOS 根据路径显示/取消屏蔽图像?

swift - SwiftUI 中的 `Task` 和 `async` 有什么区别

ios - Swift 相当于 PackageInfo 和 ApplicationInfo