今天我们就来自定义一个的画板!github地址:https://github.com/belong571/DrawView
1、效果图:
此画板使用UIBezierPath(贝塞尔曲线)实现,有清除、回退、橡皮擦、保存图片等功能。
2、代码实现如下:
自定义一个UIView子类(DrawView),重写View中touch相关方法,以下为DrawView.m文件
#import "DrawView.h" #import "MyUIBezierPath.h" @interface DrawView() @property(nonatomic,strong) NSMutableArray *paths;//此数组用来管理画板上所有的路径 @end @implementation DrawView -(NSArray *)paths{ if(!_paths){ _paths=[NSMutableArray array]; } return _paths; } //清除 - (void)clean{ [self.paths removeAllObjects]; //重绘 [self setNeedsDisplay]; } //回退 - (void)undo{ [self.paths removeLastObject]; //重绘 [self setNeedsDisplay]; } //橡皮擦 - (void)eraser{ _lineColor=self.backgroundColor; } //保存 - (void)save{ //开启图片上下文 UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0); //获取上下文 CGContextRef context=UIGraphicsGetCurrentContext(); //截屏 [self.layer renderInContext:context]; //获取图片 UIImage *image= UIGraphicsGetImageFromCurrentImageContext(); //关闭图片上下文 UIGraphicsEndImageContext(); //保存到相册 UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil); } //保存图片的回调 - (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{ NSString *message = @""; if (!error) { message = @"成功保存到相册"; }else{ message = [error description]; } NSLog(@"message is %@",message); } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ // 获取触摸对象 UITouch *touch=[touches anyObject]; // 获取手指的位置 CGPoint point=[touch locationInView:touch.view]; //当手指按下的时候就创建一条路径 MyUIBezierPath *path=[MyUIBezierPath bezierPath]; //设置画笔宽度 if(_lineWidth<=0){ [path setLineWidth:5]; }else{ [path setLineWidth:_lineWidth]; } //设置画笔颜色 [path setLineColor:_lineColor]; //设置起点 [path moveToPoint:point]; // 把每一次新创建的路径 添加到数组当中 [self.paths addObject:path]; } -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ // 获取触摸对象 UITouch *touch=[touches anyObject]; // 获取手指的位置 CGPoint point=[touch locationInView:touch.view]; // 连线的点 [[self.paths lastObject] addLineToPoint:point]; // 重绘 [self setNeedsDisplay]; } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code for (MyUIBezierPath *path in self.paths) { //设置颜色 [path.lineColor set]; // 设置连接处的样式 [path setLineJoinStyle:kCGLineJoinRound]; // 设置头尾的样式 [path setLineCapStyle:kCGLineCapRound]; //渲染 [path stroke]; } } @end
3、简单使用:
//可以通过代码创建或者绑定到storyboard上的UIView DrawView *drawView=[[DrawView alloc] init]; drawView.frame=CGRectMake(0, 100, self.view.bounds.size.width, 300); [self.view addSubview:drawView]; //设置画板背景颜色 drawView.backgroundColor=[UIColor blackColor]; //设置画笔宽度 drawView.lineWidth=5; //设置画笔颜色 drawView.lineColor=[UIColor redColor];