UIBezierPath繪制路徑
- (UIBezierPath *)path
{
if (!_path) {
_path = [UIBezierPath bezierPath];
}
return _path;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 獲取手觸摸點
UITouch *touch = [touches anyObject];
CGPoint currentP = [touch locationInView:self];
// 路徑起點
[self.path moveToPoint:currentP];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 獲取手觸摸點
UITouch *touch = [touches anyObject];
CGPoint currentP = [touch locationInView:self];
// 不斷添加點到某根線
[self.path addLineToPoint:currentP];
// 繪制出來
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
// 把路徑畫出來
[self.path stroke];
}
搞一個和路徑一樣大的圖層,繪制到屏幕上
// 跟著路徑動畫
- (void)startAnim
{
CAShapeLayer *layer = [CAShapeLayer layer];
layer.path = self.path.CGPath;
// 填充顏色沪伙,最后一個封閉的形狀
layer.fillColor = [UIColor whiteColor].CGColor;
// 描邊顏色
layer.strokeColor = [UIColor redColor].CGColor;
// 只畫一部分
// layer.strokeEnd = 0.5;
// 改變圖層的某個熟悉
CABasicAnimation *anim = [CABasicAnimation animation];
anim.keyPath = @"strokeEnd";
anim.fromValue = @0;
anim.toValue = @1;
anim.duration = 5;
[layer addAnimation:anim forKey:nil];
[self.layer addSublayer:layer];
// 清空畫線,圖形還在,和路徑一樣圖層
[self clearAll];
}
- (void)clearAll
{
[self.path removeAllPoints];
[self setNeedsDisplay];
}