在畫面上拖曳滑鼠(手指)畫出一個矩形框,放開後跳出提示視窗詢問是否儲存,選擇「是」就把框內的區塊裁切出來存進系統相簿,再到相簿中確認結果。

@property (weak, nonatomic) IBOutlet UIImageView *imageView; @property (nonatomic, weak) UIView *clipView;
- (UIView *)clipView {
if (_clipView == nil) {
UIView *view = [[UIView alloc] init];
_clipView = view;
view.backgroundColor = [UIColor blackColor];
view.alpha = 0.5; // 半透明才能看到底下的圖
[self.view addSubview:_clipView]; // 此時尚未設 frame,所以看不見
}
return _clipView;
}
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]; [self.view addGestureRecognizer:pan];
- (void)pan:(UIPanGestureRecognizer *)pan {
CGPoint endPoint = CGPointZero;
if (pan.state == UIGestureRecognizerStateBegan) {
self.startPoint = [pan locationInView:self.view]; // 記住起點
} else if (pan.state == UIGestureRecognizerStateChanged) {
endPoint = [pan locationInView:self.view]; // 動態更新終點
CGFloat w = endPoint.x - self.startPoint.x;
CGFloat h = endPoint.y - self.startPoint.y;
self.clipView.frame = CGRectMake(self.startPoint.x, self.startPoint.y, w, h);
} else if (pan.state == UIGestureRecognizerStateEnded) {
// 開啟與裁切框等大的位圖上下文
UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, 0);
// 建立封閉路徑並限制繪圖範圍
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.clipView.frame];
[path addClip];
// 把圖層渲染進目前上下文
CGContextRef context = UIGraphicsGetCurrentContext();
[self.imageView.layer renderInContext:context];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.clipView removeFromSuperview];
self.clipView = nil;
self.imageView.image = image;
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"保存圖片"
message:@"是否將圖片保存至相冊?" delegate:self
cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
[alertView show];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) { // 點了「是」
UIImageWriteToSavedPhotosAlbum(self.imageView.image, nil, nil, nil);
}
}
若要更嚴謹,可以把第三個參數換成 callback 的 selector,在 image:didFinishSavingWithError:contextInfo: 中依 error 判斷是否真的存成功,再給使用者提示。