我有以下代码段:
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的大小,但是如果我从Camera(例如,在iPhone7 +上)拍摄图片,我的imageWidth和imageHeight为:226.4 - 283.0
,这会使我的UIImageView在屏幕中央很小屏幕,如下所示:
我想做的是让originalImageView
的宽度更大并相应地保持其缩放比例(如下面的模型所示),可以吗?
答案 0 :(得分:2)
我认为,当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
}
答案 1 :(得分:0)
您需要将UIImageView
的宽度和高度设置为您希望它在屏幕上显示的尺寸,然后将UIImageView
的{{1}}设置为{{1} }或contentMode
(如果您希望它填充整个视图)。
https://developer.apple.com/documentation/uikit/uiimageview https://developer.apple.com/documentation/uikit/uiview/contentmode/scaleaspectfit