How to zoom to the center with a scrollview?

霸气de小男生 提交于 2019-12-03 22:17:30
Lindsey

We got it working and I thought I'd post what we ended up doing

 /**
 Function for the scrollview to be able to zoom out
 **/

-(IBAction)zoomOut {

    float newScale = [scrollView zoomScale] / ZOOM_STEP;
    [self handleZoomWith:newScale andZoomType: FALSE];
}

/**
 Function for the scrollview to be able to zoom in
 **/

-(IBAction)zoomIn {

    float newScale = [scrollView zoomScale] * ZOOM_STEP;
    [self handleZoomWith:newScale andZoomType: TRUE];
}

-(void)handleZoomWith: (float) newScale andZoomType:(BOOL) isZoomIn {

    CGPoint newOrigin = [zoomHandler getNewOriginFromViewLocation: [scrollView contentOffset] 
                                                         viewSize: scrSize andZoomType: isZoomIn];
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:newOrigin];
    [scrollView zoomToRect:zoomRect animated:YES];
}

and then in a zoomHandler class we had this

-(CGPoint) getNewOriginFromViewLocation: (CGPoint) oldOrigin 
                               viewSize: (CGPoint) viewSize
                            andZoomType:(BOOL) isZoomIn {

    /* calculate original center (add the half of the width/height of the screen) */ 
    float oldCenterX = oldOrigin.x + (viewSize.x / 2);
    float oldCenterY = oldOrigin.y + (viewSize.y / 2);

    /* calculate the new center */
    CGPoint newCenter;
    if(isZoomIn) {
        newCenter = CGPointMake(oldCenterX * zoomLevel, oldCenterY * zoomLevel);
    } else {
        newCenter = CGPointMake(oldCenterX / zoomLevel, oldCenterY / zoomLevel);
    }

    /* calculate the new origin (deduct the half of the width/height of the screen) */
    float newOriginX = newCenter.x - (viewSize.x / 2);
    float newOriginY = newCenter.y - (viewSize.y / 2);

    return CGPointMake(newOriginX, newOriginY);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!