缩小但不放大 SwiftUI 图像 [英] Downsize but not upsize a SwiftUI image
本文介绍了缩小但不放大 SwiftUI 图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个个人资料图片(各种尺寸)的列表,我希望每个图片都缩小以适应其视图,但我不希望它们被放大和像素化.相反,我希望小图像保持它们的分辨率.我怎样才能做到这一点?
I have a list of profile images (of various sizes) that I want each one to downsize to fit into its view, but I don't want them to be upsized and be pixilated. Instead, I want small images to stay at the resolution they are at. How do I can achieve this?
这是我到目前为止一直在使用的(但它调整了大小):
This is what I've been using so far (but it resizes up):
VStack {
Image(...)
.resizable()
.scaledToFill()
}.frame(width:200, height:200)
推荐答案
我也没有在 API 中找到简单的解决方案,所以这里有一个看起来适合我的占位符.作品有点复杂.
I did not find simple solution in API either, so here is a placeholder that looks appropriate for me. It is a bit complicated by works.
使用 Xcode 11.2+/iOS 13.2+ 测试.
Tested with Xcode 11.2+ / iOS 13.2+.
使用演示:
struct DemoImagePlaceholder_Previews: PreviewProvider {
static var previews: some View {
VStack {
ImagePlaceholder(image: Image("icon"), size: CGSize(width: 200, height: 200))
.border(Color.red)
ImagePlaceholder(image: Image("large_image"), size: CGSize(width: 200, height: 200))
.border(Color.red)
}
}
}
解决方案:
struct OriginalImageRect {
var rect: Anchor<CGRect>? = nil
}
struct OriginalImageRectKey: PreferenceKey {
static var defaultValue: OriginalImageRect = OriginalImageRect()
static func reduce(value: inout OriginalImageRect, nextValue: () -> OriginalImageRect) {
value = nextValue()
}
}
struct ImagePlaceholder: View {
let image: Image
let size: CGSize
var body: some View {
VStack {
self.image.opacity(0)
.anchorPreference(key: OriginalImageRectKey.self, value: .bounds) {
OriginalImageRect(rect: $0)
}
}
.frame(width: size.width, height: size.height)
.overlayPreferenceValue(OriginalImageRectKey.self) { pref in
GeometryReader { gp -> Image in
if pref.rect != nil, CGRect(origin: .zero, size: gp.size).contains(gp[pref.rect!]) {
return self.image
} else {
return self.image.resizable() // .fill by default, otherwise needs to wrap in AnyView
}
}
}
}
}
这篇关于缩小但不放大 SwiftUI 图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文