如果我理解你试图做的事情的话,那么我认为你完全可以使用核心动画来实现。
如果你正在移动的模式就像这样简单,那么你可以在CAShapeLayer上使用线段模式来绘制该模式。我创建了我的层,使其从边界的高度获取线宽,并且形状层的路径从该层的边界获取起始点和结束点:
CAShapeLayer *lineLayer = [CAShapeLayer layer];
lineLayer.bounds = CGRectMake(0, 0, 200, 60);
lineLayer.position = self.view.center;
lineLayer.strokeColor = [UIColor blackColor].CGColor;
lineLayer.lineDashPattern = @[@5, @2, @2, @2, @2, @2, @2, @2, @2, @2];
lineLayer.lineWidth = CGRectGetHeight(lineLayer.bounds);
UIBezierPath *linePath = [UIBezierPath bezierPath];
[linePath moveToPoint:CGPointMake(0, CGRectGetMidY(lineLayer.bounds))];
[linePath addLineToPoint:CGPointMake(CGRectGetMaxX(lineLayer.bounds), CGRectGetMidY(lineLayer.bounds))];
lineLayer.path = linePath.CGPath;
[self.view.layer addSublayer:lineLayer];
这将生成该图案的静态绘图。代码中的虚线模式是交替显示线条和不显示线条的段落长度。
![输入图像描述](https://istack.dev59.com/0Usti.webp)
绘制路径后,我通过改变线段的“相位”(将其向一个方向或另一个方向移动)来进行动画处理。为了使图案看起来平稳连续地移动,我创建了一个线性重复动画,按其完整长度移动图案:
NSNumber *totalDashLenght = [lineLayer.lineDashPattern valueForKeyPath:@"@sum.self"]; // KVC is awesome :)
CABasicAnimation *animatePhase = [CABasicAnimation animationWithKeyPath:@"lineDashPhase"];
animatePhase.byValue = totalDashLenght; // using byValue means that even if the layer has a shifted phase, it will shift on top of that.
animatePhase.duration = 3.0;
animatePhase.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animatePhase.repeatCount = INFINITY;
[lineLayer addAnimation:animatePhase forKey:@"marching ants"];
动画线看起来像这样:
![enter image description here](https://istack.dev59.com/xE1e5.gif)
如果您想让不同的线以不同的速度动画,可以更改动画的
duration
。该值表示将一个完整的相位移动动画所需的时间。