繁体   English   中英

如何在 UIImageView 中获得 UIImage 的 x 和 y position?

[英]How to get x and y position of UIImage in UIImageView?

当我们使用 scaleAspectFill 将其设置在 UIImageView 中时,我想获得 UIImage 的原始 x 和 y position。

正如我们在 scaleAspectFill 中所知道的,某些部分被剪裁了。 因此,根据我的要求,我想获得 x 和 y 值(可能是 - 我不知道的值。)。

这是来自画廊的原始图片

原始图像

现在我将上面的图像设置为我的应用程序视图。

在我看来剪辑的图像

所以在上述情况下,我想得到它隐藏的 x, y position 被剪裁的图像。

谁能告诉我如何获得它?

使用以下扩展名

extension UIImageView {

    var imageRect: CGRect {
        guard let imageSize = self.image?.size else { return self.frame }

        let scale = UIScreen.main.scale

        let imageWidth = (imageSize.width / scale).rounded()
        let frameWidth = self.frame.width.rounded()

        let imageHeight = (imageSize.height / scale).rounded()
        let frameHeight = self.frame.height.rounded()

        let ratio = max(frameWidth / imageWidth, frameHeight / imageHeight)
        let newSize = CGSize(width: imageWidth * ratio, height: imageHeight * ratio)
        let newOrigin = CGPoint(x: self.center.x - (newSize.width / 2), y: self.center.y - (newSize.height / 2))
        return CGRect(origin: newOrigin, size: newSize)
    }

}

用法

let rect = imageView.imageRect
print(rect)

界面测试

let testView = UIView(frame: rect)
testView.backgroundColor = UIColor.red.withAlphaComponent(0.5)
imageView.superview?.addSubview(testView)

使用以下扩展在 ImageView 中找出 Image 的准确细节。

extension UIImageView {
    var contentRect: CGRect {
        guard let image = image else { return bounds }
        guard contentMode == .scaleAspectFit else { return bounds }
        guard image.size.width > 0 && image.size.height > 0 else { return bounds }

        let scale: CGFloat
        if image.size.width > image.size.height {
            scale = bounds.width / image.size.width
        } else {
            scale = bounds.height / image.size.height
        }

        let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
        let x = (bounds.width - size.width) / 2.0
        let y = (bounds.height - size.height) / 2.0

        return CGRect(x: x, y: y, width: size.width, height: size.height)
    }
}

如何测试

let rect = imgTest.contentRect
print("Image rect:", rect)

如果你想像画廊中显示的那样显示图像,那么你可以使用约束“H:|[v0]|” 和 "V:|[v0]|" 并在 imageview 中使用 .aspectFit

如果你想要图像大小,你可以使用 imageView.image!.size 并计算被剪切的图像量。 在 aspectFill 中,宽度与屏幕宽度匹配,因此高度增加。 所以我想你可以找到有多少图像被切割。

试试这个库ImageCoordinateSpace

我不确定它是否适合您,但它具有将 CGPoint 从图像坐标转换为任何视图坐标的功能,反之亦然。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM