ios 如何在SwiftUI中将线条放置在圆的边缘?

nkoocmlb  于 11个月前  发布在  iOS
关注(0)|答案(1)|浏览(89)

我有一个圆,我想在圆的边缘放置小矩形。我想矩形放置在边缘只定义的Angular 。即如果Angular 是90,矩形应该在圆的顶部中心。如果说120,它应该放置在一个小的前面90度的矩形沿着有一点倾斜,所以矩形和圆形应该是同步的。我已经试了很多方法来解决这个问题,但我还无法破解这个问题。
下面是我到目前为止写的代码。它基本上是一个启动代码,仅此而已。

struct ContentView: View {
    var body: some View {
        GeometryReader { geo in
            VStack {
                ZStack {
                    Circle()
                        .stroke(lineWidth: 10)
                        .frame(width: 220)
                    Rectangle()
                        .frame(width: 15, height: 50)
                        .position(x: 0, y: 0)
                } //ZStack
                .frame(width: 220, height: 220, alignment: .center)
                .background(Color.green)
            } //VStack
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.blue)
        }
    }
}

字符串


的数据
任何帮助将不胜感激

a14dhokn

a14dhokn1#

我建议对矩形应用.offset,然后应用.rotationEffect
就像这样:

struct ContentView: View {

    let radius: CGFloat = 110
    let tickMarkLength: CGFloat = 50

    private func tickMark(degrees: CGFloat) -> some View {
        Rectangle()
            .frame(width: 15, height: tickMarkLength)
            .offset(y: -radius - (tickMarkLength / 2))
            .rotationEffect(.degrees(degrees - 90))
    }

    var body: some View {
        ZStack {
            Circle()
                .stroke(lineWidth: 10)
                .frame(width: radius * 2, height: radius * 2)
                .background(
                    Circle().fill(.green)
                )
            tickMark(degrees: 90)
            tickMark(degrees: 120)
        }
        .frame(
            width: (radius * 2) + (tickMarkLength * 2),
            height: (radius * 2) + (tickMarkLength * 2)
        )
        .background(.blue)
    }
}

字符串


的数据
在你在问题中提供的代码中,你有一个GeometryReader,尽管它似乎没有任何用途。但是,如果你打算从包含它的框架的大小导出圆的半径,那么这也是可能的。需要一些小的修改:

struct ContentView: View {
    let tickMarkLength: CGFloat = 50

    private func tickMark(radius: CGFloat, degrees: CGFloat) -> some View {
        // implementation as before
    }

    var body: some View {
        GeometryReader { geo in
            let radius = (geo.size.height / 2) - tickMarkLength
            ZStack {
                Circle()
                    // modifiers as before
                tickMark(radius: radius, degrees: 90)
                tickMark(radius: radius, degrees: 120)
            }
            .frame(width: geo.size.width, height: geo.size.height)
        }
        .frame(width: 320, height: 320) // just an example
        .background(.blue)
    }
}

相关问题