Path中的boundingRect未在SwiftUI中输出任何内容

brccelvz  于 2022-12-26  发布在  Swift
关注(0)|答案(1)|浏览(115)

我试图为Path创建一个函数,将帧分成两半。

extension Path {
    mutating func divideInHalf() {
        move(to: CGPoint(x: 0, y: boundingRect.midY))
        addLine(to: CGPoint(x: boundingRect.maxX, y: boundingRect.midY))
    }
}

然而,这似乎什么也做不了。事实上,我试着用boundingRect做实验,但它根本拒绝输出任何东西。

struct ContentView: View {
    @State private var text = "waiting for value..."
    
    var body: some View {
        VStack {
            Text(text)  // This stays as "waiting for value..."
            Path { path in
                path.divideInHalf()
                text = "\(path.boundingRect.height)"  // This does nothing
            }
            .stroke()
        }
    }
}

我想这可能与使用inout变量有关,所以我也尝试这样做:

struct ContentView: View {
    @State private var text = "waiting for value..."
    
    var body: some View {
        VStack {
            Text(text)  // This stays as "waiting for value..."
            Path { path in
                path.divideInHalf()
                let rect = Path { path in 
                    path.move(to: .zero)
                    path.addLine(to: CGPoint(x: 100, y: 100))
                }.boundingRect  // Getting the value from the instance directly

                text = "\(rect.height)"  // This still does nothing
            }
            .stroke()
        }
    }
}

我试着在路径中添加更多的行,但仍然没有任何效果。有人知道boundingRect是如何工作的吗?为什么它没有输出任何东西,我错过了什么?

q1qsirdb

q1qsirdb1#

PathboundingRect是多少?

print(Path { _ in }.boundingRect)
/// (inf, inf, 0.0, 0.0)

divideInHalf中,对moveaddLine的调用传递的是midYmaxX,它们都是CGFloat.inf(无穷大)。Path似乎会忽略此类调用。
如果您在Path中放入一些内容,divideInHalf将添加一个子路径。例如:

struct ContentView: View {
    var body: some View {
        VStack {
            Path { path in
                path.addEllipse(in: .init(x: 10, y: 10, width: 100, height: 100))
                path.divideInHalf()
            }
            .stroke()
            .frame(width: 200, height: 200)
            .border(.red)
        }
    }
}

PlaygroundPage.current.setLiveView(ContentView())

穿过圆的水平线是divideInHalf的结果:

请注意,如果将divideInHalf中的move调用更改为使用boundingRect.minX而不是0,您可能会更喜欢结果。

相关问题