在touchesBegan
方法中初始化一个CAShapeLayer:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
CGPoint point = [self pointWithTouches:touches];
if (event.allTouches.count == 1) {
[self initStartPath:point];
}
}
- (CGPoint)pointWithTouches:(NSSet<UITouch *> *)touches{
UITouch *touch = (UITouch *)touches.anyObject;
return [touch locationInView:self.view];
}
初始化CAShapeLayer:
- (void)initStartPath:(CGPoint)startPoint{
UIBezierPath *path = [[UIBezierPath alloc] init];
path.lineWidth = 2;
// 线条拐角
path.lineCapStyle = kCGLineCapRound;
// 终点处理
path.lineJoinStyle = kCGLineJoinRound;
[path moveToPoint:startPoint];
self.lastPath = path;
CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
shapeLayer.path = path.CGPath;
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.lineCap = kCALineCapRound;
shapeLayer.lineJoin = kCALineJoinRound;
shapeLayer.strokeColor = [UIColor redColor].CGColor;
shapeLayer.lineWidth = path.lineWidth;
self.lastLayer = shapeLayer;
[self.view.layer addSublayer:shapeLayer];
}```
在```touchesMoved```方法中更新贝塞尔曲线的路径
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
CGPoint point = [self pointWithTouches:touches];
if (event.allTouches.count == 1) {
[self.lastPath addLineToPoint:point];
self.lastLayer.path = self.lastPath.CGPath;
}
}
运行效果:
![画板.gif](http://upload-images.jianshu.io/upload_images/2666834-bbc6a861b2674bb4.gif?imageMogr2/auto-orient/strip)