...
1 #import "ViewController.h" 2 #import "SecondVC.h" 3 4 5 #define WIDTH [UIScreen mainScreen].bounds.size.width 6 #define HEIGHT [UIScreen mainScreen].bounds.size.height 7 8 @interface ViewController () 9 { 10 UIImageView *_canvasView;//畫布 11 CGPoint _startPoint;//記錄開始坐標 12 13 } 14 @end 15 16 @implementation ViewController 17 18 - (void)viewDidLoad { 19 [super viewDidLoad]; 20 21 _canvasView = [[UIImageView alloc] initWithFrame:self.view.bounds]; 22 [self.view addSubview:_canvasView]; 23 24 UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 25 clearBtn.frame = CGRectMake(50, 20, 100, 30); 26 [clearBtn addTarget:self action:@selector(clearBtnClick) forControlEvents:UIControlEventTouchUpInside]; 27 [clearBtn setTitle:@"清空" forState:UIControlStateNormal]; 28 clearBtn.backgroundColor = [UIColor orangeColor]; 29 [self.view addSubview:clearBtn]; 30 31 UIButton *cutPicBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 32 cutPicBtn.frame = CGRectMake(250, 20, 100, 30); 33 [cutPicBtn addTarget:self action:@selector(cutPicBtnClick) forControlEvents:UIControlEventTouchUpInside]; 34 [cutPicBtn setTitle:@"截圖" forState:UIControlStateNormal]; 35 cutPicBtn.backgroundColor = [UIColor orangeColor]; 36 [self.view addSubview:cutPicBtn]; 37 38 } 39 40 41 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 42 { 43 _startPoint = [[touches anyObject] locationInView:_canvasView]; 44 45 } 46 47 - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 48 { 49 CGPoint movePoint = [[touches anyObject] locationInView:_canvasView]; 50 51 // 移動的點有很多, 52 @autoreleasepool { 53 UIGraphicsBeginImageContext(CGSizeMake(WIDTH, HEIGHT));//開始一個圖片的繪圖 54 55 [_canvasView drawRect:_canvasView.frame];//繪製原來已經存在的線條 56 57 CGContextRef context = UIGraphicsGetCurrentContext();//繪圖緩存區,當前的是一張圖片 58 CGContextSetLineWidth(context, 5); 59 CGContextSetRGBStrokeColor(context, 1, 0, 0, 1); 60 CGContextSetLineCap(context, kCGLineCapRound);//邊帽 61 CGContextSetLineJoin(context, kCGLineJoinRound);//縫合 62 63 CGContextMoveToPoint(context, _startPoint.x, _startPoint.y); 64 CGContextAddLineToPoint(context, movePoint.x, movePoint.y); 65 CGContextStrokePath(context); 66 _canvasView.image = UIGraphicsGetImageFromCurrentImageContext();//獲取當前圖片繪製區域內的圖片 67 68 UIGraphicsEndImageContext();//關閉圖片繪製 69 } 70 71 _startPoint = movePoint; 72 } 73 74 75 #pragma mark - 清除按鈕 76 - (void)clearBtnClick 77 { 78 79 _canvasView.image = nil;//這並不是一個好辦法。 80 81 } 82 83 #pragma mark - 剪切按鈕 84 - (void)cutPicBtnClick 85 { 86 UIGraphicsBeginImageContext(CGSizeMake(WIDTH, HEIGHT));//開始一個圖片的繪圖 87 // 在屏幕載入之後截圖 88 [self.view drawViewHierarchyInRect:self.view.frame afterScreenUpdates:YES]; 89 90 UIImage *image = UIGraphicsGetImageFromCurrentImageContext();//獲取當前圖片繪製區域內的圖片 91 92 UIGraphicsEndImageContext(); 93 94 SecondVC *vc = [[SecondVC alloc] init]; 95 vc.image = image; 96 [self presentViewController:vc animated:YES completion:nil]; 97 }