![](/img/trans.png)
[英]How to resize UIImageView based on UIImage's size/ratio in Swift 3?
[英]How to resize a UIImageView based on UIImage size and fit the screen's width
我有这个代码片段:
func resizeImageViewToImageSize(_ imageView:UIImageView) {
let widthRatio = imageView.bounds.size.width / imageView.image!.size.width
let heightRatio = imageView.bounds.size.height / imageView.image!.size.height
let scale = min(widthRatio, heightRatio)
let imageWidth = scale * imageView.image!.size.width
let imageHeight = scale * imageView.image!.size.height
print("\(imageWidth) - \(imageHeight)")
imageView.frame = CGRect(x: 0,
y: 70,
width: imageWidth,
height: imageHeight)
imageView.center.x = view.center.x
}
我在viewDidLoad()
调用它来调整我originalImageView
UIImageView 的大小:
resizeImageViewToImageSize(originalImageView)
它成功地调整了我的 UIImageView 的大小,但如果我从相机(例如在 iPhone7+ 上)拍摄照片,我的 imageWidth 和 imageHeight 是: 226.4 - 283.0
,这使得我的 UIImageView 在屏幕中央非常小,如下所示:
我想要做的是让我的originalImageView
宽度更大,并相应地保持其缩放比例,如下面的模型,这可能吗?
我认为当值的问题出现imageView.image!.size.width
大于imageView.bounds.size.width
或高度值。
这将导致widthRatio
或heightRatio
的值小于1。
当scale
小于1并乘以imageWidth
和imageHeight
,最终得到的UIImageView将小于原始图像。
我猜想像iPhone7一样,从相机拍摄的图像的分辨率会很高。
你必须检查其值越高imageView.bounds.width
或imageView.image!.size.width
,然后拿到取决于条件的倒数。
func resizeImageViewToImageSize(_ imageView:UIImageView) {
let maxWidth = view.frame.size.width
let maxHeight = view.frame.size.height
var widthRatio = imageView.bounds.size.width / imageView.image!.size.width
if widthRatio < 1 {
widthRatio = 1 / widthRatio
}
let heightRatio = imageView.bounds.size.height / imageView.image!.size.height
if heightRatio < 1 {
heightRatio = 1 / widthRatio
}
let scale = min(widthRatio, heightRatio)
let maxWidthRatio = maxWidth / imageView.bounds.size.width
let maxHeightRatio = maxHeight / imageView.bounds.size.height
let maxScale = min(maxWidthRatio, maxHeightRatio)
let properScale = min(scale, maxScale)
let imageWidth = properScale * imageView.image!.size.width
let imageHeight = properScale * imageView.image!.size.height
print("\(imageWidth) - \(imageHeight)")
imageView.frame = CGRect(x: 0,
y: 70,
width: imageWidth,
height: imageHeight)
imageView.center.x = view.center.x
}
您需要将UIImageView
的宽度和高度设置为希望它在屏幕上占据的大小,然后将UIImageView
的contentMode
为UIView.ContentMode.scaleAspectFit
或UIView.ContentMode.scaleAspectFill
,以使其填充整个屏幕视图。
https://developer.apple.com/documentation/uikit/uiimageview https://developer.apple.com/documentation/uikit/uiview/contentmode/scaleaspectfit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.