Pankaj Gaikar
Pankaj Gaikar

Reputation: 2483

SwiftUI - How to apply aspectFit to image so it does not go outside of designated area

I am trying to fit a square shaped image in rectangle shaped ImageView. With storyboard, I can easily do it with content mode .aspectFit but I am unable to figure out how to do it with SwiftUI.

I am currently doing something like this:

    Image("BG")
        .resizable()
        .aspectRatio(contentMode: .fill)
        .scaledToFill()
        .clipped()
        .frame(height: 200)

which gives below output, notice the blue border is my actual ImageView:

enter image description here

However, I am expecting something like this which I did in storyboard: enter image description here

Upvotes: 3

Views: 455

Answers (1)

Asperi
Asperi

Reputation: 257779

You need to clip it after set size, like

Image("BG")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .scaledToFill()
    .frame(height: 200)
    .clipped()               // << here !!

Upvotes: 2

Related Questions