在 iOS 中展示圖片時,除了單純顯示,還常需要縮放、移動與裁切。這類互動常用於圖片預覽、文件掃描或影像辨識前的範圍選擇。
先將圖片載入 UIImageView,並將視圖尺寸設為圖片原始尺寸,讓內容完整呈現。
UIImage *image = [UIImage imageNamed:@"sample.jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
[self.view addSubview:imageView];
可以使用 UIPinchGestureRecognizer 處理雙指縮放,透過 transform 調整視圖比例。
CGAffineTransform transform = CGAffineTransformScale(CGAffineTransformIdentity, scale, scale);
imageView.transform = transform;
使用 UIPanGestureRecognizer 可以讓使用者拖曳畫面。
CGPoint location = [gesture locationInView:self.view];
imageView.center = location;
若需要對目前顯示區域進行裁切,可以先把畫面渲染成 UIImage。
UIGraphicsBeginImageContext(view.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[view.layer renderInContext:context];
UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
取得截圖後,可以使用 CGImageCreateWithImageInRect 裁切。
CGRect cropRect = CGRectMake(x, y, width, height);
CGImageRef imageRef = CGImageCreateWithImageInRect([snapshot CGImage], cropRect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
若希望使用者以手指畫出矩形範圍,可以自訂 UIView,在 touchesBegan、touchesMoved 與 touchesEnded 中記錄座標,並以 UIBezierPath 或 Core Graphics 繪製外框。最後將框選範圍轉成 CGRect,再進行裁切。
這類功能的關鍵在於座標系一致性。只要縮放、移動與截圖的座標轉換處理得當,就能穩定地做出直覺的裁切體驗。