实现虚线动画
效果就是下面这张图循环动起来:

实现:
/**
* lineView: 需要绘制成虚线的view
* lineLength: 虚线的宽度
* lineSpacing: 虚线的间距
* lineColor: 虚线的颜色
**/
- (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
{
// 设置路径
UIBezierPath *path = [UIBezierPath bezierPathWithRect:lineView.bounds];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:lineView.bounds];
[shapeLayer setFillColor:[UIColor clearColor].CGColor];
// 设置虚线颜色为blackColor
[shapeLayer setStrokeColor:lineColor.CGColor];
// 设置虚线宽度
[shapeLayer setLineWidth:3.f];
// 设置线条圆角
[shapeLayer setLineCap:kCALineJoinRound];
// 设置线宽,线间距
[shapeLayer setLineDashPattern:[NSArray arrayWithObjects:@(lineLength),@(lineSpacing), nil]];
//设置路径
[shapeLayer setPath:path.CGPath];
[lineView.layer addSublayer:shapeLayer];
//加动画
CABasicAnimation *dashAnimation = [CABasicAnimation
animationWithKeyPath:@"lineDashPhase"];
[dashAnimation setFromValue:[NSNumber numberWithFloat:0.0f]];
[dashAnimation setToValue:[NSNumber numberWithFloat:300.f]];
[dashAnimation setDuration:4.f];
dashAnimation.cumulative = YES; //关键属性,自己看文档
[dashAnimation setRepeatCount:MAXFLOAT];
dashAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[shapeLayer addAnimation:dashAnimation forKey:@"linePhase"];
}
加载实现:
UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(self.view.center.x, self.view.center.y, 100,100)];
[self.view addSubview:lineView];
[self drawDashLine:lineView lineLength:16 lineSpacing:15 lineColor:[UIColor redColor]];
网友评论