Search code examples
iosswiftuiscrollviewcgpoint

Find CGPoint of view inside UIScrollView depending of UIScrollView's center point


I have a UIScrollView with an UIImageView inside. The main goal is to move the UIImageView inside de UIScrollView like drag, zoom, etc.

Let's imagine that scrollview's frame is 100x100. The UIImageView's size in 250x100. So, we can drag from left to right without zooming, and we when zoom in, we can drag from top to bottom.

  • I know the center of the UIScrollView = (50,50) => CGPoint

My question is: how can I get the CGPoint of the UIImageView equivalent to the center CGPoint of the scrollview ?

Here is, I hope, an helpful description of the scene:

enter image description here

Thank you a lot for your help guys!


Solution

  • Thanks to rmaddy for you help.

    Here is the solution:

    //FYI: focusPoint.scale is the zoomScale of the UIScrollView.
    let originVisible = scrollView.contentOffset
    let convertedPoint = scrollView.convert(originVisible, to: imageView).scaledBy(scale: focusPoint.scale)
    let imageViewPoint = CGPoint(x: convertedPoint.x + scrollView.center.x,
                                 y: convertedPoint.y + scrollView.center.y)
    
    extension CGPoint {
        func scaledBy(scale: CGFloat) -> CGPoint {
            return CGPoint(x: x * scale, y: y * scale)
        }
    }