Search code examples
iosswiftuiimageviewuiimage

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


I want to get original x and y position of UIImage when we set it in UIImageView with scaleAspectFill.

As we know in scaleAspectFill, some of the portion is clipped. So as per my requirement I want to get x and y value (it may be - value I don't know.).

Here is the original image from gallery

original image

Now I am setting this above image to my app view.

Clipped image in my view

So as above situation, I want to get it's hidden x, y position of image which are clipped.

Can any one tell how to get it?


Solution

  • Use following extension

    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)
        }
    
    }
    

    Usage

    let rect = imageView.imageRect
    print(rect)
    

    UI Test

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