动态获取imageview的位置
Get the position of imageview dynamically
我需要获取图像视图的动态 x,y 位置。
这个我试过了
self.imgView.bounds.origin.y
和
self.imgView.frame.origin.x
我一直都是 0.0。
我怎样才能得到这个?
谢谢
请使用下面的代码在 UIImageVIew
中获取 rect
此代码在 swift3 并且您的 ImageViewContentMode 应该是 Aspect fit
func calculateRectOfImageInImageView(imageView: UIImageView) -> CGRect {
let imageViewSize = imageView.frame.size
let imgSize = imageView.image?.size
guard let imageSize = imgSize, imgSize != nil else {
return CGRect.zero
}
let scaleWidth = imageViewSize.width / imageSize.width
let scaleHeight = imageViewSize.height / imageSize.height
let aspect = fmin(scaleWidth, scaleHeight)
var imageRect = CGRect(x: 0, y: 0, width: imageSize.width * aspect, height: imageSize.height * aspect)
// Center image
imageRect.origin.x = (imageViewSize.width - imageRect.size.width) / 2
imageRect.origin.y = (imageViewSize.height - imageRect.size.height) / 2
// Add imageView offset
imageRect.origin.x += imageView.frame.origin.x
imageRect.origin.y += imageView.frame.origin.y
return imageRect
}
任何视图的bounds.origin在任何时候都应该是(0,0),因为它是视图本身的坐标系(相对于它的原点)
frame.origin在它的父视图的坐标系中,所以如果它是0,0,那可能是它的原点在它的父视图的原点。
也许您想知道屏幕的来源?如果是这样,
let posInWindow = v.convert(v.bounds.origin, to: nil)
边界将始终return x 和 y 为 0,您想使用框架。在您的示例中,这些值可能是正确的?尝试在视图中心添加您的 imageView 并记录:
self.imgView.frame.origin.x
self.imgView.frame.origin.y
我需要获取图像视图的动态 x,y 位置。 这个我试过了
self.imgView.bounds.origin.y
和
self.imgView.frame.origin.x
我一直都是 0.0。
我怎样才能得到这个?
谢谢
请使用下面的代码在 UIImageVIew
中获取 rect
此代码在 swift3 并且您的 ImageViewContentMode 应该是 Aspect fit
func calculateRectOfImageInImageView(imageView: UIImageView) -> CGRect {
let imageViewSize = imageView.frame.size
let imgSize = imageView.image?.size
guard let imageSize = imgSize, imgSize != nil else {
return CGRect.zero
}
let scaleWidth = imageViewSize.width / imageSize.width
let scaleHeight = imageViewSize.height / imageSize.height
let aspect = fmin(scaleWidth, scaleHeight)
var imageRect = CGRect(x: 0, y: 0, width: imageSize.width * aspect, height: imageSize.height * aspect)
// Center image
imageRect.origin.x = (imageViewSize.width - imageRect.size.width) / 2
imageRect.origin.y = (imageViewSize.height - imageRect.size.height) / 2
// Add imageView offset
imageRect.origin.x += imageView.frame.origin.x
imageRect.origin.y += imageView.frame.origin.y
return imageRect
}
任何视图的bounds.origin在任何时候都应该是(0,0),因为它是视图本身的坐标系(相对于它的原点)
frame.origin在它的父视图的坐标系中,所以如果它是0,0,那可能是它的原点在它的父视图的原点。
也许您想知道屏幕的来源?如果是这样,
let posInWindow = v.convert(v.bounds.origin, to: nil)
边界将始终return x 和 y 为 0,您想使用框架。在您的示例中,这些值可能是正确的?尝试在视图中心添加您的 imageView 并记录:
self.imgView.frame.origin.x
self.imgView.frame.origin.y