定义一个继承于NSObject的model对象,用于存储
线的颜色,路径及线宽
#import <Foundation/Foundation.h> #import <UIKit/UIKit.h>//一定导入UIKit框架 @interface PathModel : NSObject @property(nonatomic,assign)CGMutablePathRef path;//路径(需要调用set方法retain) @property(nonatomic,strong)UIColor *color;//颜色 @property(nonatomic,assign)CGFloat lineWidth;//线宽 @end //记得要将路径计数值加一,复写set方法 #import "PathModel.h" @implementation PathModel -(void)dealloc { CGPathRelease(_path); } - (void)setPath:(CGMutablePathRef)path { //使路径的计数值加一,这样在DrawView中释放路径后,model中仍然存在,不会出现野指针 CGPathRetain(path); _path = path; } @end
DrawView中的实现代码
#import "DrawView.h" #import "PathModel.h" @implementation DrawView -(instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { //设置默认值 _lineWidth = 1; _color = [UIColor blackColor]; } return self; } - (void)drawRect:(CGRect)rect { //如果可变数组不是空的,则需要重新绘制之前的路径 if (_pathArray.count>0) { for (int i = 0; i<_pathArray.count; i++) { //遍历数组中的所有元素 取出model中的属性并绘制之前的线条 PathModel *model = _pathArray[i]; CGContextRef context = UIGraphicsGetCurrentContext(); CGMutablePathRef path = model.path; UIColor *color = model.color; CGFloat width = model.lineWidth; //绘制 CGContextAddPath(context, path); //设置填充颜色 [color set]; //设置线宽 CGContextSetLineWidth(context, width); //设置头尾及连接点的类型为圆的, CGContextSetLineJoin(context, kCGLineJoinRound); CGContextSetLineCap(context, kCGLineCapRound); CGContextDrawPath(context, kCGPathStroke); } } //当_LinePath不为空的时候,说明开始绘制新的线条,颜色和线宽就是在视图控制器中通过block块传递过来的参数 if (_LinePath != nil) { CGContextRef context = UIGraphicsGetCurrentContext(); [_color set]; CGContextSetLineWidth(context, _lineWidth); CGContextAddPath(context, _LinePath); CGContextDrawPath(context, kCGPathStroke); } } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //取得手指开始触摸的点的坐标 CGPoint p = [[touches anyObject] locationInView:self]; //创建路径 _LinePath = CGPathCreateMutable(); //获得路径开始的点的坐标 CGPathMoveToPoint(_LinePath, NULL, p.x, p.y); } -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { //获得手指一动过程中经过的点的坐标 CGPoint p = [[touches anyObject]locationInView:self]; //将这些点添加到路径中 CGPathAddLineToPoint(_LinePath, NULL, p.x,p.y); //重新绘制 [self setNeedsDisplay]; } -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { //创建一个可变数组,存放model对象,(model中有颜色,线宽,路径三个属性) if (_pathArray==nil) { _pathArray = [[NSMutableArray alloc]init]; } //创建model对象,并且给model中的属性赋值 PathModel *model = [[PathModel alloc]init]; model.path = _LinePath; model.lineWidth = _lineWidth; model.color = _color; //将model存放到可变数组中 [_pathArray addObject:model]; //手指结束触摸时将路径释放掉 CGPathRelease(_LinePath); _LinePath = nil; } - (void)undo { if (_pathArray.count>0) { [_pathArray removeLastObject]; [self setNeedsDisplay]; } } - (void)clear { if (_pathArray.count>0) { [_pathArray removeAllObjects]; [self setNeedsDisplay]; } } @end
效果图
时间: 2024-10-15 06:15:26