I'm trying to draw text with a filled and inset rectangle under the text that matches the text's size inside a Canvas in SwiftUI, but I'm unable to figure out how to get the dimensions of the Text view.
struct ContentView: View {
var body : some View {
Canvas { context,size in
let TEXT = Text("Some text").foregroundColor(.black)
// context.fill(TEXT.boundingRect.insetBy(dx: -4, dy: -2), with: .color(.red)) // error: no boundingRect
context.draw(TEXT, at: CGPoint(x: size.width/2,y: size.height/2))
}
}
}
You need ask the
GraphicsContextto ‘resolve’ theText. You can then ask theResolvedTextto measure itself.Output:
I found that I needed to make the type of the
textvariable explicit (let text: Text). Otherwise, the compiler infers typesome View, which can't be resolved.