[英]Make UIImageView fit width of screen but keep aspect ratio [swift]
[英]UIImageView keep aspect ratio, but fit to width
我認為最好的方法是使用 imageView 的模式(縱橫比填充、縱橫寬等),這是基於圖像的寬度和高度之間的比率
if image.width > image.height {
imageView.contentMode = UIViewContentModeScaleAspectFit
//since the width > height we may fit it and we'll have bands on top/bottom
} else {
imageView.contentMode = UIViewContentModeScaleAspectFill
//width < height we fill it until width is taken up and clipped on top/bottom
}
UIViewContentModeScaleAspectFit
通過保持縱橫比縮放內容以適應視圖的大小。 視圖邊界的任何剩余區域都是透明的。
UIViewContentModeScaleAspectFill
縮放內容以填充視圖的大小。 內容的某些部分可能會被裁剪以填充視圖的邊界。
我還沒有測試過,但我覺得這似乎是對的
我認為您需要將圖像縱橫比與 UIImageView 本身的縱橫比進行比較:
private func updateUI() {
guard let image = image else { return }
let viewAspectRatio = self.bounds.width / self.bounds.height
let imageAspectRatio = image.size.width / image.size.height
if viewAspectRatio > imageAspectRatio {
self.contentMode = .scaleAspectFill
} else {
self.contentMode = .scaleAspectFit
}
}
override var image: UIImage? { didSet { updateUI() }}
override func layoutSubviews() {
super.layoutSubviews()
updateUI()
}
注意:這是方面適合寬度
斯威夫特 5.1 iOS 13
因為我的位於集合視圖的標題單元格上,所以這對我有用:
if headerCell!.imageView.frame.width > headerCell!.imageView.frame.height {
headerCell!.imageView.contentMode = .scaleAspectFit
//since the width > height we may fit it and we'll have bands on top/bottom
} else {
headerCell!.imageView.contentMode = .scaleAspectFill
//width < height we fill it until width is taken up and clipped on top/bottom
}
對於我的情況下的解決辦法是設置UIImageView
的contentMode
基於如果圖像的高度和寬度的比率大於的更大imageView
的。
func setupImageViewContentMode() {
if let image = imageView.image, image.size.height / image.size.width > imageView.frame.height / imageView.frame.width {
imageView.contentMode = .scaleAspectFit
} else {
imageView.contentMode = .scaleAspectFill
}
}
另外,請注意,您必須根據當前布局進行設置,因此在從后端或任何您需要的地方加載圖像后,例如在layoutSubviews()
、 viewDidLayoutSubviews()
調用此方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.