This should be simple - so simple I'm pretty sure I've missed something obvious!
I want to have some text with a circle drawn round it. The tricky part is making the frame of the view be that of the circle, not the frame of the text.
Here is what I have at the moment:
struct CircledText: View {
let text: String
var body: some View {
Text(text)
.padding()
.background(Circle()
.strokeBorder()
.aspectRatio(1, contentMode: .fill))
.border(.orange)
}
}
but this doesn't make the frame of the view match the circle - the frame is the frame of the text+padding.
Here are three previews with different length text.

How can I create a view so that the bounds of the view equal that of the circle, not the text?
You can look at this way:
struct ContentView: View {
var body: some View {
CircledText(text: "Hello, world!")
.border(Color.orange)
}
}
struct CircledText: View {
let text: String
@State private var radius: CGFloat = .zero
var body: some View {
return ZStack {
Text(text)
.padding()
.background(GeometryReader { proxy in Color.clear.onAppear() { radius = max(proxy.size.width, proxy.size.height) } }.hidden())
if (!radius.isZero) {
Circle().strokeBorder().frame(width: radius, height: radius)
}
}
}
}

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With