屬性
/**貝塞爾曲線 */
@property (nonatomic, retain) UIBezierPath *bezier;
/**用來記錄線的位置*/
@property (nonatomic, retain) NSMutableArray *beziers;
/** 子layer層*/
@property (nonatomic, retain) CALayer *subLayer;```
######自定義初始化
-(CALayer *)subLayer{
if (!_subLayer) {
self.subLayer = [[CALayer alloc] init];
self.subLayer.backgroundColor = [UIColor redColor].CGColor;
self.subLayer.bounds = CGRectMake(0, 0, 10, 10);
self.subLayer.cornerRadius = 5;
[self.layer addSublayer:_subLayer];
}
return _subLayer;
}
-(NSMutableArray *)beziers{
if (!_beziers) {
self.beziers = [NSMutableArray array]; }
return _beziers; }
-(CGPoint)getPointFromTouches:(NSSet<UITouch *> *)touches{
UITouch * touch = [touches anyObject];
CGPoint curP = [touch locationInView:self];
return curP;
}
###### 想實現(xiàn)畫圖的功能
// 1 自定義View
// 2 實現(xiàn)touch相關(guān)的方法
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
CGPoint curp =
[self getPointFromTouches:touches];
// 繪圖相關(guān)的類( UIBezierPath 貝塞爾曲線)
self.bezier = [UIBezierPath bezierPath];
// 開始點
[self.bezier moveToPoint:curp];
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
CGPoint moveP = [self getPointFromTouches:touches];
[self.bezier addLineToPoint:moveP];
self.bezier.lineWidth = 5;
// 手動調(diào)用
[self setNeedsDisplay];
// 把每次的貝塞爾曲線添加到數(shù)組里
[self.beziers addObject:self.bezier];
}
-(void)start{
// 關(guān)鍵幀動畫
CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
animation.keyPath = @"position";
// 動畫的路徑為貝塞爾曲線
animation.path = self.bezier.CGPath;
animation.repeatCount = MAXFLOAT;
animation.duration = 10;
// 將動畫添加到子layer層
[self.subLayer addAnimation:animation forKey:nil];
// CAReplicatorLayer 復(fù)制圖層
}
/** 在UIView上繪圖的系統(tǒng)方法*/
-(void)drawRect:(CGRect)rect{
for (UIBezierPath *path in self.beziers) {
[path stroke];
}
}