我必须尝试所有类型的内容模式,第三方和大量的谷歌搜索。 但是,对我来说不是成功。 我想像脸书图片帖子一样显示。 我们在Facebook上发布图像,Facebook正确显示图像并将图像非常正确地填充到图像视图中。
按照步骤操作
- setImage to UIImageView (带
UIViewContentModeScaleAspectFit
( - 获取图像大小
(CGSize imageSize = imageView.image.size)
- UIImageView 调整大小。
[imageView sizeThatFits:imageSize]
-
将位置移动到所需位置。
CGSize imageSize = imageView.image.size; [imageView sizeThatFits:imageSize]; CGPoint imageViewCenter = imageView.center; imageViewCenter.x = CGRectGetMidX(self.contentView.frame); [imageView setCenter:imageViewCenter];
设置 UIImageView 大小 == 图像(比率(:
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
@IBOutlet weak var widthConstraint: NSLayoutConstraint!
func setImage(image: UIImage) {
imageView.image = image
let screenSize = UIScreen.main.bounds.size
let imageAspectRatio = image.size.width / image.size.height
let screenAspectRatio = screenSize.width / screenSize.height
if imageAspectRatio > screenAspectRatio {
widthConstraint.constant = min(image.size.width, screenSize.width)
heightConstraint.constant = widthConstraint.constant / imageAspectRatio
}
else {
heightConstraint.constant = min(image.size.height, screenSize.height)
widthConstraint.constant = heightConstraint.constant * imageAspectRatio
}
view.layoutIfNeeded()
}
参考链接 自动布局:UIImageView 和宽高比拟合内容模式