问题描述
我有一个 imageView,它的框架是 (47.0,415.66666666666674,320.0,320.0)
,它的 y 原点是 415
lazy var imageView: UIImageView = {
let imgView = UIImageView()
// ...
imgView.contentMode = .aspectScaleFit
}
要在我使用的 imageView 中获取图像的矩形:
view.layoutIfNeeded()
let imageRect = AVMakeRect(aspectRatio: imageView.image!.size,insideRect: imageView.bounds)
print(imageRect) // (-47.0,-358.2753623188407,205.21739130434787)
当我尝试转换 imageRect 以找出它在窗口坐标系内的位置时
let frameInWindow = imageView.convert(imageRect,from: nil)
print(frameInWindow) // (-47.0,205.21739130434787)
我有两个问题:
1- 为什么 x
和 y
值为负 -47
和 -358
为了获得正 y 值,我使用了 let yPosition = abs(frameInWindow.origin.y)
,它给了我 358
的 yPosition,但是它高于 imageView 的 y 位置。
2- 为什么 yPosition 不是 425 之类的东西,或者考虑到图像的中心设置在 imageView 的中心,并且因为图像小于 imageView,所以它的 y.origin 应该低于 415( Window 中 imageView 的 y 值)
解决方法
当您说 imageView.convert(imageRect,from: nil)
时,您正在将 imageRect
从窗口坐标转换为图像视图的坐标。但是 imageRect
不在窗口的坐标中,所以没有意义。