简体   繁体   中英

How to setup Image with SwiftUI that resize automatically with ratio 1:1?

This is what i have in code:

var number: Int {
    if isLargeWidget {
        return 5
    }
    if isSmallWidget {
        return 3
    }
    return 3
}
var body: some View {
    VStack(alignment: .leading, spacing: 0) {
        ForEach(entry.newses.prefix(number)) { news in
            HStack(alignment: .center, spacing: 10) {
                NetworkImage(url: URL(string: news.image))
                Text("news.title")
                    .foregroundColor(textColor)
                    .font(Font.openSansRegular(withSize: 14))
            }
            .padding(.leading, 0)
            .frame(width: .infinity)
        }
    }
    .frame(width: .infinity)
    .padding(.all, 0)
    .background(backgroundColor)
}

and the result is like this:

在此处输入图像描述

What to do to set image ratio to 1:1 for every row?

struct NetworkImage: View {
    let url: URL?
    var body: some View {
        if let url = url, let imageData = try? Data(contentsOf: url), let uiImage = UIImage(data: imageData) {
            Image(uiImage: uiImage)
                .centerCropped()
        }
    }
}
extension Image {
    func centerCropped() -> some View {
        GeometryReader { geo in
            self
            .resizable()
            .scaledToFill()
                .frame(width: geo.size.width, height: geo.size.height)
            .clipped()
        }
    }
}

To scale the Image you can use aspectRatio :

Image("image")
    .resizable()
    .aspectRatio(contentMode: .fit)

If you also want to force the aspect ratio, you can do:

Image("image")
    .resizable()
    .aspectRatio(1, contentMode: .fit)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM