2

In my iOS 14 Widget I want to display several circular images in a row.

When using scaledToFit() the image stretches weirdly to fit the circle. scaledToFill() gives me the desired output like so:

Image("Person")
    .resizable()
    .scaledToFill()
    .clipShape(Circle())

But this changes the behaviour of the view to ignore it's parent and expand beyond it. Setting a fixed frame prevents this, but I need these Images to resize dynamically. When I place this View inside an HStack in my Widget the Images are way too large.

How can I get the image to scale like scaledToFill() and still respect the parent view.

3 Answers 3

3

I found it works best when wrapping the GeometryReader directly into the Image

HStack {
    GeometryReader { geo in
        Image("Person")
          .resizable()
          .scaledToFill()
          .frame(width: geo.size.width, height: geo.size.height)
    }
}

1
  • This should be accepted answer Commented Sep 2 at 16:23
0

You can try using geometry reader. This is an example code of what I have used in my Widget so you have to adjust it for your project, however, you will get the idea.

GeometryReader { geo in
        ZStack(alignment: .bottom) {
        HStack {
               Image("Person")
                    .resizable()
                    .frame(width: geo.size.width, height: geo.size.height)
                    .aspectRatio(contentMode: .fit)
            }
        }
    }
0

I found a solution in this post, the first answer works great in the Widget:

stackoverflow.com/questions/58290963/clip-image-to-square-in-swiftui

However I am reusing the view within my app and it caused some weird behaviour there. Instead I am now clipping the Image to a Circle before the View is created. This allows me to use .scaledToFit() and still maintain the original aspect ratio of the image.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.