Search code examples
swiftswiftui

SwiftUI modify image frame


I have an image that I would like to always use the maximum available width. However the image should have a max height of 500 and should only utilize the height if it will fill it. Currently wide images dont fill the full height but the images frame is still 500 and hence why the text views are far away from the image. When the image is taller the width is not all used. How can I use the correct modifiers for this need?

import SwiftUI
import Kingfisher

struct SwiftUIView: View {
    var body: some View {
        VStack {
            Text("hello")
            KFImage(URL(string: "https://letsenhance.io/static/8f5e523ee6b2479e26ecc91b9c25261e/1015f/MainAfter.jpg"))
                .resizable()
                .scaledToFit()
                .clipShape(RoundedRectangle(cornerRadius: 15))
                .contentShape(RoundedRectangle(cornerRadius: 15))
                .frame(maxHeight: 500)
                .clipped()
            Text("hello")
           
        }
        .padding(.horizontal, 20)
    }
}


//image: smaller width, larger height
//"https://media.macphun.com/img/uploads/customer/how-to/608/15542038745ca344e267fb80.28757312.jpg?q=85&w=1340"

#Preview {
    SwiftUIView()
}
Current result

Demo


Solution

  • You question is a bit vague to me

    1️⃣ First Though: Same Width - Same Height

    If I understand you correctly, You are looking for kind ofFill behavior like this:

    Wide Tall

    You can use a placeholder view and use the image inside it's overlay like:

    VStack {
        Text("hello")
    
        Color.clear // 👈 use it as a placeholder view
            .overlay (
                KFImage(URL(string: "https://letsenhance.io/static/8f5e523ee6b2479e26ecc91b9c25261e/1015f/MainAfter.jpg"))
                    .resizable()
                    .scaledToFill() // 👈 Fill instead of Fit
            )
            .frame(maxHeight: 500) // 👈 Apply modifications on the container
            .clipShape(RoundedRectangle(cornerRadius: 15))
            .contentShape(RoundedRectangle(cornerRadius: 15))
            .clipped()
    
        Text("hello")
    
    }
    .padding(.horizontal, 20)
    

    2️⃣ Second Though: Same Width - Fit Content's Height

    If you just need to fit the height of the image container to the image content like this:

    Wide2 Tall2

    You just need to add one more modifier:

    KFImage(URL(string: "https://media.macphun.com/img/uploads/customer/how-to/608/15542038745ca344e267fb80.28757312.jpg?q=85&w=1340"))
        .resizable()
        .scaledToFit()
        .clipShape(RoundedRectangle(cornerRadius: 15))
        .contentShape(RoundedRectangle(cornerRadius: 15))
        .frame(maxHeight: 500)
        .fixedSize(horizontal: false, vertical: true) // 👈 Add this one here
        .clipped()