我试图为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
是如何工作的吗?为什么它没有输出任何东西,我错过了什么?
1条答案
按热度按时间q1qsirdb1#
空
Path
的boundingRect
是多少?在
divideInHalf
中,对move
和addLine
的调用传递的是midY
和maxX
,它们都是CGFloat.inf
(无穷大)。Path
似乎会忽略此类调用。如果您在
Path
中放入一些内容,divideInHalf
将添加一个子路径。例如:穿过圆的水平线是
divideInHalf
的结果:请注意,如果将
divideInHalf
中的move
调用更改为使用boundingRect.minX
而不是0
,您可能会更喜欢结果。