简体   繁体   English

如何使用 SwiftUI 以 1:1 的比例自动调整大小的图像?

[英]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?如何将每行的图像比例设置为 1:1?

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 ,您可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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