如何使用 SwiftUI 绘制圆弧?

How to draw an arc with SwiftUI?

我想用 SwiftUI 画一个弧形。我一直在寻找类似用于 Circle() 的段修饰符之类的东西,但找不到。我应该可以设置开始和结束角度。

可以用Path画弧

首先定义路径

let arc = UIBezierPath(arcCenter: CGPoint(x: 0, y: 0),
                              radius: 60,
                              startAngle: .pi ,
                              endAngle: 0.2,
                              clockwise: true)

然后

            Path(arc.cgPath).foregroundColor(Color.blue)

你真的应该检查一下:https://developer.apple.com/tutorials/swiftui/drawing-paths-and-shapes

这是一个快捷方式:

import SwiftUI

struct ContentView : View {
    var body: some View {
        MyShape()
    }
}

struct MyShape : Shape {
    func path(in rect: CGRect) -> Path {
        var p = Path()

        p.addArc(center: CGPoint(x: 100, y:100), radius: 50, startAngle: .degrees(0), endAngle: .degrees(90), clockwise: true)

        return p.strokedPath(.init(lineWidth: 3, dash: [5, 3], dashPhase: 10))
    }    
}

此问题的另一种解决方案可以通过以下方式完成:

Circle()
   .trim(from: 0.25, to: 1.0)
   .rotation(.degrees(-90))
   .stroke(Color.black ,style: StrokeStyle(lineWidth: 3, lineCap: .butt, dash: [5,3], dashPhase: 10))
   .frame(width: 52, height: 52) 

这将产生:

根据您要执行的操作,您可以选择进行轮换。这显然可以扩展为视图修改器,具体取决于您的用例以及是否需要它(这看起来很简单)。