一個簡單的繪圖應用,模仿蘋果自帶軟件備忘錄里的塗鴉功能
核心代碼
#import "DrawView.h" #import "DrawPath.h" @interface DrawView () @property (nonatomic, strong) NSMutableArray *paths; @property (nonatomic, strong) UIBezierPath *path; @end @implementation DrawView - (void)setImage:(UIImage *)image { _image = image; [self.paths addObject:image]; [self setNeedsDisplay]; } // 撤銷 - (void)undo { [self.paths removeLastObject]; [self setNeedsDisplay]; } - (void)clear { // 清除畫板view所有的路徑,並且重繪 [self.paths removeAllObjects]; [self setNeedsDisplay]; } - (void)awakeFromNib { _lineWidth = 1; _lineColor = [UIColor blackColor]; } - (NSMutableArray *)paths { if (_paths == nil) { _paths = [NSMutableArray array]; } return _paths; } // 當手指點擊view,就需要記錄下起始點 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { // 獲取UITouch UITouch *touch = [touches anyObject]; // 獲取起始點 CGPoint curP = [touch locationInView:self]; // 只要一開始觸摸控件,設置起始點 DrawPath *path = [DrawPath path]; path.lineColor = _lineColor; [path moveToPoint:curP]; path.lineWidth = _lineWidth; // 記錄當前正在描述的路徑 _path = path; // 保存當前的路徑 [self.paths addObject:path]; } // 每次手指移動的時候調用 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { // 獲取UITouch UITouch *touch = [touches anyObject]; // 獲取當前觸摸點 CGPoint curP = [touch locationInView:self]; [_path addLineToPoint:curP]; // 重繪 [self setNeedsDisplay]; } // 繪制東西 - (void)drawRect:(CGRect)rect { for (DrawPath *path in self.paths) { if ([path isKindOfClass:[UIImage class]]) { // 圖片 UIImage *image = (UIImage *)path; [image drawAtPoint:CGPointZero]; }else{ [path.lineColor set]; [path stroke]; } } } @end
用法很簡單,導入DrawView.h DrawView.m 文件創建該控件即可
清屏: [_drawView clear];
撤銷: [_drawView undo];
橡皮擦: _drawView.lineColor = [UIColor whiteColor];
github地址:https://github.com/chglog/scrawl