本文示範如何利用 UIScrollView 完成圖片縮放。核心機制其實只有一個 delegate 方法:
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return self.zoomImageView;
}
你只要告訴 scrollView「哪個子 view 可以被縮放」,它就會在 minimumZoomScale 與 maximumZoomScale 之間,對該 view 套用 transform 縮放。scrollView 內部如何處理座標換算與內容對齊,可以不必深究;關鍵是把三個屬性設定對:delegate、minimumZoomScale、maximumZoomScale。
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.delegate = self;
self.showsVerticalScrollIndicator = NO;
self.showsHorizontalScrollIndicator = NO;
self.maximumZoomScale = 3;
self.zoomImageView = [[[UIImageView alloc] init] autorelease];
self.zoomImageView.userInteractionEnabled = YES;
self.zoomImageView.frame = CGRectMake(0.0f, 0.0f,
frame.size.width, frame.size.height);
self.zoomImageView.image = [UIImage imageNamed:@"lichengwu.jpeg"];
[self addSubview:self.zoomImageView];
// 雙擊縮放手勢
UITapGestureRecognizer *doubleTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleDoubleTap:)];
[doubleTap setNumberOfTapsRequired:2];
[self.zoomImageView addGestureRecognizer:doubleTap];
[doubleTap release];
tapClicks = NO;
}
return self;
}
注意 userInteractionEnabled = YES 這一行:UIImageView 預設是 NO,若不打開,加上去的手勢永遠不會被觸發。這是最常見的疏漏。
- (void)handleDoubleTap:(UIGestureRecognizer *)gesture {
float newScale = tapClicks ? self.zoomScale * 2.0 : 1.0;
CGRect zoomRect = [self zoomRectForScale:newScale
withCenter:[gesture locationInView:gesture.view]];
[self zoomToRect:zoomRect animated:YES];
tapClicks = !tapClicks;
}
用一個布林值在「放大兩倍」與「還原」之間切換。注意原範例把縮小分支寫成 zoomScale * 0.0,這會算出 0 倍而導致圖片消失,應該改為回到 1.0 才是正確的還原行為。
- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center {
CGRect zoomRect;
zoomRect.size.height = self.frame.size.height / scale;
zoomRect.size.width = self.frame.size.width / scale;
zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0);
zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
return zoomRect;
}
原理是:先算出「放大 scale 倍後,畫面上相當於整個可視區域的那塊矩形有多大」,再以點擊位置為中心把矩形擺正,最後交給 scrollView 去縮放並捲動到該區域。使用者輕點哪裡,就以哪裡為中心放大,體感自然。
1. 縮放時讓圖片置中。 當縮小後的圖片比 scrollView 還小時,圖會黏在左上角。實作 scrollViewDidZoom: 並調整 zoomImageView 的 center,使其在兩個軸向都置中:
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
CGSize contentSize = scrollView.contentSize;
CGSize boundsSize = scrollView.bounds.size;
if (contentSize.width < boundsSize.width) {
CGFloat dx = (boundsSize.width - contentSize.width) / 2;
// 調整 center.x
}
}
2. contentInset 也值得考慮。 在 iOS 11 之後,若 scrollView 是整個畫面,記得處理 contentInsetAdjustmentBehavior,否則縮放後的位置會受安全區域影響而偏移。
3. 圖片解析度要足夠。 若原圖解析度低於 maximumZoomScale 放大後的顯示尺寸,放大就會模糊。 Photo viewer 類型的 App 通常會依當前縮放比例切換載入不同解析度的圖。
4. 轉動的慣性。 若想做出照片 App 那種「放大後拖到邊緣會自動捲回」的效果,需要實作 scrollViewDidEndDragging:willDecelerate: 並自行邊界約束,UIScrollView 預設沒有這個行為。