2011-04-29 72 views
5

我在UIScrollView中有一個UIImageView。我希望用戶可以縮放和導航圖像。在縮小時在屏幕上居中顯示UIImageView

這是我的工作代碼:

//img is the UIImageView 
//scroller is the UIScrollView 

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { 
return img; 
} 
- (void)viewDidLoad { 
    [super viewDidLoad]; 
    UIImage *image = [UIImage imageNamed:@"map_screen.png"]; 
    img = [[UIImageView alloc] initWithImage:image]; 
    scroller.delegate = self; 
    scroller.autoresizesSubviews = YES; 
    scroller.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; 
    scroller.contentSize = img.frame.size; 
    scroller.scrollEnabled = YES; 
    scroller.directionalLockEnabled = NO; 
    scroller.userInteractionEnabled = YES; 

    CGSize ivsize = img.frame.size; 
    CGSize ssize = scroller.frame.size; 

    float scalex = ssize.width/ivsize.width; 
    float scaley = ssize.height/ivsize.height; 
    scroller.minimumZoomScale = fmin(1.0, fmax(scaley, scalex)); 
    scroller.zoomScale = fmin(1.0, fmax(scalex, scaley)); 
    [scroller addSubview:img]; 
    img.userInteractionEnabled = YES; 
} 

所有作品,但是這個事情發生了:最小變焦屏幕的高度。 我的圖像的寬度比高度大,所以我希望最小縮放是寬度。

如果我寫

scroller.minimumZoomScale = fmin(1.0, scalex); 

的作品,但是當用戶縮小,圖像不在屏幕中央,但在頂部。

我已經嘗試過這樣的事情

CGPoint scrollCenter = [scroller center]; 
[img setCenter:CGPointMake(scrollCenter.x, scrollCenter.y)]; 

img.center = scroller.center; 

,但這種解決方案,圖像不完全地滾動,如果我縮小,它在頂部再次入住的屏幕,但不完全可見!

我該如何解決它?

回答

10

你必須做手工,而變焦是在使用scrollViewDidZoom委託函數的進展...像

- (void)scrollViewDidZoom:(UIScrollView *)scrollView 
{ 

    // center the image as it becomes smaller than the size of the screen 
    CGSize boundsSize = scrollView.bounds.size; 
    CGRect frameToCenter = imageView.frame; 

    // center horizontally 
    if (frameToCenter.size.width < boundsSize.width) 
    { 
     frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width)/2; 
    } else { 
     frameToCenter.origin.x = 0; 
    } 

    // center vertically 
    if (frameToCenter.size.height < boundsSize.height) 
    { 
     frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height)/2; 
    } else { 
     frameToCenter.origin.y = 0; 
    } 

    imageView.frame = frameToCenter; 

} 
+0

對!有用!謝謝!!! – JAA 2011-04-29 16:25:36

1

迅速3.0版本巴斯蒂安的答案,多了幾分簡潔:

func scrollViewDidZoom(_ scrollView: UIScrollView) { 
    // center the image as it becomes smaller than the size of the screen 
    let boundsSize = scrollView.bounds.size 
    var frameToCenter = imageView.frame 

    // center horizontally and vertically 
    let widthDiff = boundsSize.width - frameToCenter.size.width 
    let heightDiff = boundsSize.height - frameToCenter.size.height 
    frameToCenter.origin.x = (widthDiff > 0) ? widthDiff/2 : 0; 
    frameToCenter.origin.y = (heightDiff > 0) ? heightDiff/2 : 0; 

    imageView.frame = frameToCenter; 
}