如何解决SwiftUI:KFImage、aspectRatio() 和 layoutPriority()
我在使用 KFImage
时遇到了一些问题。它适用于占位符图像,直到加载远程图像。似乎是 .aspectRatio()
和 .layoutPriority(-1)
之间的某种互动。
我有一种带有图像的卡片,下面有几个文本块。我希望将图像裁剪为具有特定纵横比的视图,其宽度由容器决定(在实际应用程序中,它们位于网格中,并且大小因设备而异。我希望图像为增长,而不是增长的间距)。
这是我使用占位符(气泡)和加载的图像(纵横比测试图像)得到的结果。占位符图片为654 x 768,加载的图片为1080 x 1920。占位符的纵横比保持得当,剪裁成想要的纵横比。
但正如您所看到的,加载的图像被非均匀缩放以适应与占位符相同的纵横比。对此的正常解决方案是添加 .aspectRatio(.fill)
。但是如果我在 KFImage
上这样做,它会破坏一切:
这是代码。注意 .aspectRatio(contentMode: .fill)
上的 KFImage
被注释掉了。如果你取消注释,你会得到上面的第二张图片。
import SwiftUI
import Kingfisher
struct
SellerShowCell: View
{
let title : String
let secondary : String?
var startTime : Date? = nil
var thumbnailURL : URL? = nil
var
body: some View {
vstack(alignment: .leading,spacing: 0.0) {
ZStack(alignment: .topLeading) {
// Thumbnail background…
ZStack {
KFImage(self.thumbnailURL)
.cancelOndisappear(true)
.placeholder {
ZStack {
Color(.black)
Image("image_placeholder_background")
.resizable()
.aspectRatio(contentMode: .fill)
.layoutPriority(-1)
}
}
.resizable()
// .aspectRatio(contentMode: .fill) // Uncommenting this ruins the placeholder and allows the loaded image to dictate the parent size
// .layoutPriority(-1) // This does not have any obvIoUs effect on KFImage
}
.aspectRatio(158.0 / 220.0,contentMode: .fit)
.cornerRadius(16.0)
Text("A Note")
.foregroundColor(.white)
.padding(8.0)
.background(Color.purple)
.clipShape(Capsule())
.padding([.top,.leading],10.0)
}
// Title…
Text("\(self.title)")
.multilineTextAlignment(.leading)
.lineLimit(2)
.font(.custom("Helvetica",size: 16.0).weight(.semibold))
.foregroundColor(.black)
.padding(.top,12.0)
// Secondary…
if let secondary = self.secondary {
Text("\(secondary)")
.multilineTextAlignment(.leading)
.font(.custom("Helvetica Neue",size: 12.0).weight(.medium))
.foregroundColor(Color("secondary-color"))
.padding(.top,12.0)
}
}
.border(Color.green)
}
}
struct SellerShowCell_Previews: PreviewProvider {
static var previews: some View {
ZStack {
Color("main-tab-background")
.ignoresSafeArea()
vstack(spacing: 20.0) {
SellerShowCell(title: "Here is a caption of sufficient length to be a couple of lines",secondary: "Secondary Text",thumbnailURL: nil)
.padding(.horizontal,80)
SellerShowCell(title: "Here is a caption of sufficient length to be a couple of lines",thumbnailURL: URL(string: "https://i.imgur.com/iH7Xe20.jpg")!)
.padding(.horizontal,80)
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。