我认为最好的方法是调整imageView的显示模式(Aspect Fill,Aspect Width等),这取决于图像宽高比。
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()
}
Swift 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
}
imageView
的比率来设置UIImageView
的contentMode
。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()
中调用此方法,在从后端加载图像或任何需要它的地方之后进行操作。