如何获取UIImage在UIImageView中的x和y位置?

时间:2019-05-20 07:26:05

标签: ios swift uiimageview uiimage

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

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

这是画廊的原始照片

original image

现在我将这张图片设置为我的应用视图。

Clipped image in my view

因此,在上述情况下,我想获取其被裁剪的图像的隐藏x,y位置。

谁能告诉我如何获得它?

3 个答案:

答案 0 :(得分:1)

使用以下扩展名

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)

UI测试

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

答案 1 :(得分:0)

如果您要显示图库中显示的图像,则可以使用约束 “ H:| [v0] |”和“ V:| [v0] |”并在imageview中使用.aspectFit

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

答案 2 :(得分:0)

使用以下扩展名可以在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)
相关问题