Search code examples
swiftswiftuiswiftui-text

How to have text fit within boundaries of circular shape/image SwiftUI


I can't seem to grasp how to make sure that my text overlays and fits within the circular image's boundaries. This is what I have so far.

Circle()
    .frame(width: 100, height: 100)
    .overlay(
        Text("Reaaaallllllyyyyyy Looooooongggggg")
            .foregroundColor(Color.red)
            .frame(minWidth: 0, maxWidth: .infinity)
        )

Text overlayed on top of circle

Is there a way in SwiftUI to get this to work? How would I go about achieving this?


Solution

  • struct ClippedCircleView: View {
        @State var text: String = "Reaaaallllllyyyyyy Looooooongggggg"
        // Make this any number you are comfortable with
        @State var letterLimit: Int = 12
        var body: some View {
            
            Circle()
                .frame(width: 100, height: 100)
                .overlay(
                    Text(text)
                        //Limit to 1 line until your letterLimit
                        .lineLimit(text.count <= letterLimit ? 1 : nil)
                        //Clips it to shape
                        .clipShape(ContainerRelativeShape()).padding()
                        .foregroundColor(Color.red)
                        //This makes super tiny letters so adjust to your use case
                        .minimumScaleFactor(0.1)
                    
                )
        }
    }