本程式結合事件處理機制與繪圖,完成一個簡單的塗鴉板應用。使用手指在塗鴉板內拖動即可作畫;點擊「保存到相簿」可將成品存到手機相簿;點擊「回退」可退回一步;點擊「清空」則清空畫布。
- (IBAction)clearOnClick:(UIButton *)sender {
[self.customView clearView]; // 清空
}
- (IBAction)backOnClick:(UIButton *)sender {
[self.customView backView]; // 回退
}
- (IBAction)saveBtnOnClick:(UIButton *)sender {
// 取得畫布的圖片
UIImage *newImage = [UIImage YYcaptureImageWithView:self.customView];
// 保存到相簿
UIImageWriteToSavedPhotosAlbum(newImage, self,
@selector(image:didFinishSavingWithError:contextInfo:), nil);
}
// 處理保存結果
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
[MBProgressHUD showError:@"塗鴉保存失敗,請檢查權限"];
} else {
[MBProgressHUD showSuccess:@"保存成功!"];
}
}
@interface YYView ()
@property(nonatomic, strong) NSMutableArray *paths; // 儲存所有路徑
@end
@implementation YYView
#pragma mark - 懶加載
-(NSMutableArray *)paths {
if (_paths == nil) {
_paths = [NSMutableArray array];
}
return _paths;
}
// 手指開始觸摸
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint starPoint = [touch locationInView:touch.view];
// 手指按下時建立一條路徑
UIBezierPath *path = [UIBezierPath bezierPath];
[path setLineWidth:5];
[path setLineJoinStyle:kCGLineJoinRound];
[path setLineCapStyle:kCGLineCapRound];
[path moveToPoint:starPoint];
[self.paths addObject:path];
}
// 手指移動
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint movePoint = [touch locationInView:touch.view];
UIBezierPath *currentPath = [self.paths lastObject];
[currentPath addLineToPoint:movePoint];
[self setNeedsDisplay]; // 重繪
}
// 畫線
- (void)drawRect:(CGRect)rect {
for (UIBezierPath *path in self.paths) {
[path stroke];
}
}
// 清空
-(void)clearView {
[self.paths removeAllObjects];
[self setNeedsDisplay];
}
// 回退
-(void)backView {
[self.paths removeLastObject];
[self setNeedsDisplay];
}
@end
// UIImage+YYcaptureView.m
+(UIImage *)YYcaptureImageWithView:(UIView *)view {
// 1. 建立 bitmap 圖形上下文
UIGraphicsBeginImageContext(view.frame.size);
// 2. 將 view 的 layer 繪製到 bitmap 上下文
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
// 3. 取出繪製好的圖片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 4. 回傳圖片
return newImage;
}
整體思路:以 NSMutableArray 保存每一筆的 UIBezierPath,手指移動時更新當前路徑並呼叫 setNeedsDisplay 觸發 drawRect: 重繪;回退即移除最後一筆,清空則移除全部路徑;保存時透過 renderInContext: 將整個 view 渲染成 UIImage 再寫入相簿。