Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a circle around Text in SwiftUI

Tags:

swiftui

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.

Three previews of the circled text

How can I create a view so that the bounds of the view equal that of the circle, not the text?

like image 244
deanWombourne Avatar asked Oct 25 '25 04:10

deanWombourne


1 Answers

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)
                
            }
            
        }
     
    }
}

enter image description here

like image 121
ios coder Avatar answered Oct 26 '25 23:10

ios coder



Donate For Us

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