Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Image scaledToFill layout behaviour

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.

like image 485
milan.elsen Avatar asked Oct 17 '25 02:10

milan.elsen


2 Answers

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

like image 146
i4guar Avatar answered Oct 20 '25 00:10

i4guar


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)
            }
        }
    }
like image 44
Dakata Avatar answered Oct 20 '25 01:10

Dakata