1

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 Answers3

1

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

i4guar
  • 599
  • 5
  • 10
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)
            }
        }
    }
Dakata
  • 1,227
  • 2
  • 14
  • 33
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.