使用SwiftUI的等距圆分割

使用SwiftUI的等距圆分割,swiftui,Swiftui,我正在尝试使用SwiftUI创建一个等间距的圆形标尺,但在使用此代码时总是出现一个小问题: struct ContentView:View{ 设magicNumber:CGFloat=20 var body:一些观点{ VStack{ GeometryReader{geo-in 圈() .stroke(颜色.red,样式:StrokeStyle(线宽:geo.size.width/5,线帽:。对接,破折号:[1,magicNumber])) .填充(地理尺寸宽度/10) } }.padding(

我正在尝试使用SwiftUI创建一个等间距的圆形标尺,但在使用此代码时总是出现一个小问题:

struct ContentView:View{
设magicNumber:CGFloat=20
var body:一些观点{
VStack{
GeometryReader{geo-in
圈()
.stroke(颜色.red,样式:StrokeStyle(线宽:geo.size.width/5,线帽:。对接,破折号:[1,magicNumber]))
.填充(地理尺寸宽度/10)
}
}.padding()
}
}
从这里可以看出


我已经分离出“magicNumber”变量,希望有一个函数/方程可以用来确定间距始终相等的条件。有什么建议吗?或者有更好的方法来实现这一点?

与其尝试动态计算一个幻数,不如定义一个形状并告诉它您需要多少个截面。这样你就可以保证它们的间隔是均匀的

struct ContentView : View {
    var body: some View {
        MyShape(sections: 20, lineLengthPercentage: 0.3)
            .stroke(Color.red)
    }
}

struct MyShape : Shape {
    var sections : Int
    var lineLengthPercentage: CGFloat
    
    func path(in rect: CGRect) -> Path {
        let radius = rect.width / 2
        let degreeSeparation : Double = 360.0 / Double(sections)
        var path = Path()
        for index in 0..<Int(360.0/degreeSeparation) {
            let degrees = Double(index) * degreeSeparation
            let center = CGPoint(x: rect.midX, y: rect.midY)
            let innerX = center.x + (radius - rect.size.width * lineLengthPercentage / 2) * CGFloat(cos(degrees / 360 * Double.pi * 2))
            let innerY = center.y + (radius - rect.size.width * lineLengthPercentage / 2) * CGFloat(sin(degrees / 360 * Double.pi * 2))
            let outerX = center.x + radius * CGFloat(cos(degrees / 360 * Double.pi * 2))
            let outerY = center.y + radius * CGFloat(sin(degrees / 360 * Double.pi * 2))
            path.move(to: CGPoint(x: innerX, y: innerY))
            path.addLine(to: CGPoint(x: outerX, y: outerY))
        }
        return path
    }
}

struct ContentView:View{
var body:一些观点{
MyShape(截面:20,线条长度百分比:0.3)
.笔划(颜色.红色)
}
}
结构MyShape:Shape{
变量部分:Int
变量lineLengthPercentage:CGFloat
func路径(在rect:CGRect中)->path{
让半径=矩形宽度/2
让度分离:双=360.0/双(截面)
var path=path()

对于0中的索引..太棒了!我将一行更改为
let radius=min(rect.width,rect.height)/2
,这样无论帧的纵横比如何,它都适用于我。干杯。