I was trying to create a function for Path that divides the frame in half.
extension Path {
mutating func divideInHalf() {
move(to: CGPoint(x: 0, y: boundingRect.midY))
addLine(to: CGPoint(x: boundingRect.maxX, y: boundingRect.midY))
}
}
However, this seemed to do nothing. In fact, I tried experimenting with boundingRect but it refused to output anything at all.
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()
}
}
}
I thought maybe it had something to do with using the inout variable so I tried doing this as well:
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()
}
}
}
I tried adding more lines to the path but that still did nothing. Does anyone know how boundingRect works? Why is it not outputting anything, what am I missing?
What is the
boundingRectof an emptyPath?In
divideInHalf, your calls tomoveandaddLineare passingmidYandmaxX, which are bothCGFloat.inf(infinity).Pathappears to ignore such calls.If you put some content in your
Path,divideInHalfwill add a subpath. For example:The horizontal line through the circle is the result of
divideInHalf:Note that you might like the result better if you change the
movecall individeInHalfto useboundingRect.minXinstead of0.