两个重点 一个设置一个
CGMutablePathRef 来存放不断变动的线条
另一个
@property (nonatomic,strong)NSMutableArray *paths;
用来存放已经画好的线条
代码如下
#import "DSNView.h"
#import "DSNPath.h"
@interface DSNView ()
@property (nonatomic,strong)NSMutableArray *paths;
@end
@implementation DSNView
{
CGPoint point;
CGMutablePathRef path;
}
-(NSMutableArray *)paths
{
if (!_paths) {
_paths = [NSMutableArray array];
}
return _paths;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
point = [touch locationInView:self];
path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, point.x, point.y);
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
point = [touch locationInView:self];
[self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
DSNPath *mPath = [[DSNPath alloc]init];
mPath.myPath = path;
[self.paths addObject:mPath];
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGPathAddLineToPoint(path, NULL, point.x, point.y);
CGContextAddPath(context, path);
CGContextStrokePath(context);
for (int i = 0; i<self.paths.count; i++) {
DSNPath *mPath = self.paths[i];
// mPath.myPath = path;
CGContextAddPath(context, mPath.myPath);
CGContextStrokePath(context);
}
}