Lapinou
Lapinou

Reputation: 1477

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.

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!

Upvotes: 0

Views: 1025

Answers (2)

Lapinou
Lapinou

Reputation: 1477

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

Upvotes: 0

rmaddy
rmaddy

Reputation: 318774

Use the convert method of UIView to convert a point from the scroll view to the image view:

let imageViewPoint = scrollView.convert(CGPoint(x: 50, y: 50), to: imageView)

Upvotes: 1

Related Questions