如何解决如何在uimageview中获得uiimage的宽高比合适大小?
当调用print(uiimage.size)时,它仅给出原始图像的宽度和高度,然后按比例放大或缩小。无论如何,要获得宽高比拟合图像的尺寸?
解决方法
您将需要Point
自己计算得出的图像尺寸*。
*事实证明您没有。参见Alladinian's answer。我要去 在这里留下这个答案,以解释库函数的作用。
这是数学:
let imageAspectRatio = image.size.width / image.size.height
let viewAspectRatio = imageView.frame.width / imageView.frame.height
var fitWidth: CGFloat // scaled width in points
var fitHeight: CGFloat // scaled height in points
var offsetX: CGFloat // horizontal gap between image and frame
var offsetY: CGFloat // vertical gap between image and frame
if imageAspectRatio <= viewAspectRatio {
// Image is narrower than view so with aspectFit,it will touch
// the top and bottom of the view,but not the sides
fitHeight = imageView.frame.height
fitWidth = fitHeight * imageAspectRatio
offsetY = 0
offsetX = (imageView.frame.width - fitWidth) / 2
} else {
// Image is wider than view so with aspectFit,it will touch
// the sides of the view but not the top and bottom
fitWidth = imageView.frame.width
fitHeight = fitWidth / imageAspectRatio
offsetX = 0
offsetY = (imageView.frame.height - fitHeight) / 2
}
说明:
它有助于绘制图片。画一个代表
imageView。然后绘制一个狭窄的矩形,但从
图像视图的顶部到底部。那是第一种情况。然后画
图像较短但延伸到图像两侧的一侧
视图。那是第二种情况。在这一点上,我们知道
尺寸。另一个就是该值乘以或除以
图片的宽高比,因为我们知道.aspectFit
保持
图片的原始宽高比。
关于frame
与bounds
的注释。 frame
在视图超级视图的坐标系中。 bounds
在视图本身的坐标系中。我选择在此示例中使用框架,因为OP对将imageView移到其Superview的坐标中感兴趣。对于尚未进一步旋转或缩放的标准imageView,框架的宽度和高度将与边界的宽度和高度匹配。当将旋转应用于imageView时,事情变得很有趣。框架将展开以显示整个imageView,但是边界保持不变。
实际上,AVFoundation
中有一个函数可以为您计算:
import AVFoundation
let fitRect = AVMakeRect(aspectRatio: image.size,insideRect: imageView.bounds)
现在fitRect.size
是通过保持原始宽高比在imageView范围内的大小。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。