Ios绘制线条动画

Jan*_*Jan 2 core-graphics ios

我有一个视图,其中我有多条水平线(像一个水平表盘).我想为水平运动制作动画.它看起来应该是这样的

编辑:

水平动画

在此输入图像描述

在此输入图像描述

我怎样才能做到这一点?据我所知,我不能使用CoreAnimation.此外,我不能模拟不同的速度.updatemethod如何工作?我是否改变了抽奖时间或距离?

我知道我可以通过scrollview解决这个问题,但我不想使用它.

谢谢!

Dav*_*ist 9

如果我已经理解了你想要做的事情,那么我认为你没有理由不能使用Core Animation来做到这一点.

如果您移动的模式非常简单,那么您可以在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];
Run Code Online (Sandbox Code Playgroud)

这将产生图案的静态绘图.代码中的线虚线图案是显示线条的位置和不显示线条的交替线段的长度.

在此输入图像描述

绘制路径后,我通过改变线破折号的"相位"(将它们向一个方向或另一个方向移动)来完成动画.为了使图像看起来像是平滑且连续移动,我创建了一个线性的重复动画,将图案的全长移动:

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"];
Run Code Online (Sandbox Code Playgroud)

动画线看起来像这样:

在此输入图像描述

如果您希望不同的线条以不同的速度进行动画处理,则可以更改duration动画.该值表示为移动一个完整阶段设置动画所需的时间.