Home > other >  SwiftUI fit text to image container
SwiftUI fit text to image container

Time:08-30

I tried to create a simple widget that is an image with text on top of it. But from time to time, text is cropped and text does not wrap to a new line (see screenshot).

What should I do to prevent it?

  var body: some View {
    ZStack {
      Image("Bg")
        .resizable()
        .aspectRatio(contentMode: .fill)
        .overlay(Color.black.opacity(0.2))
        .overlay(
          VStack {
            Text("Long text...")
              .foregroundColor(.white)
              .shadow(color: .black, radius: 20, x: 0, y: 10)
              .font(.system(size: 18))
              .padding(16)
          }
        )
    }.widgetURL(getDeepLink())
  }

enter image description here

CodePudding user response:

This happen because the overlay is set on the fill image frame. You can use overlay on Text to add image or:

Text("Long text... Long text... Long text... Long text... Long text...")
        .foregroundColor(.white)
        .shadow(color: .black, radius: 20, x: 0, y: 10)
        .font(.system(size: 18))
        .background(
             Image(systemName: "cloud")
                 .resizable()
                 .scaledToFill()
                 .edgesIgnoringSafeArea(.all))
  • Related