Find the center point of a UIScrollView when scaling

I find it difficult to get tiled UIScrollViewto zoom in and out with zoom. The problem is that when the pinch zoom appears, the resulting view is usually not centered in the same area.

Details: The application starts with a 500x500 tile image. If the user zooms in, he will be tied to 1000x1000, and the tiles will be redrawn. For all zoom effects, etc. I just let UIScrollViewit be done. When called scrollViewDidEndZooming:withView:atScale:, I redraw the fragments (as you can see in many examples and other questions here).

I think I calculated the problem before calculating the center of the view correctly when I get to scrollViewDidEndZooming:withView:atScale:(I can focus on the known fine point after redrawing).

What I'm using now:

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale {
    // as an example, create the "target" content size
    CGSize newZoomSize = CGSizeMake(1000, 1000);

    // get the center point
    CGPoint center = [scrollView contentOffset];
    center.x += [scrollView frame].width / 2;
    center.y += [scrollView frame].height / 2;

    // since pinch zoom changes the contentSize of the scroll view, translate this point to 
    // the "target" size (from the current size)
    center = [self translatePoint:center currentSize:[scrollView contentSize] newSize:newZoomSize];

    // redraw...
}

/*
    Translate the point from one size to another
*/
- (CGPoint)translatePoint:(CGPoint)origin currentSize:(CGSize)currentSize newSize:(CGSize)newSize {
    // shortcut if they are equal
    if(currentSize.width == newSize.width && currentSize.height == newSize.height){ return origin; }

    // translate
    origin.x = newSize.width * (origin.x / currentSize.width);
    origin.y = newSize.height * (origin.y / currentSize.height);
    return origin;
}

Does this sound right? Is there a better way? Thank!

+3
source share
2 answers

The way I solved it so far is to keep the starting center point of the view when starting the zoom. I first save this value when the method is called scrollViewDidScroll(and the scroll view is scaled). When called scrollViewDidEndZooming:withView:atScale:, I use this center point (and reset the saved value).

+1
source

, center contentOffset.

 aView.center = CGPointMake(
     self.scrollView.center.x + self.scrollView.contentOffset.x,
     self.scrollView.center.y + self.scrollView.contentOffset.y);
0

Source: https://habr.com/ru/post/1754327/


All Articles