我想接近以下情况:
如果我使用CGBezierPath和CAShapeLayer绘制一个矩形,如下所示:
CAShapeLayer *layerX = [CAShapeLayer layer];
layerX.path = path.CGPath;
layerX.lineWidth = 3;
layerX.strokeColor = [[UIColor whiteColor] CGColor];
layerX.fillColor = [[UIColor clearColor] CGColor];
[self.view.layer addSublayer: layerX];
我想添加动画,就像我附加的图像一样,这个被清除的区域一直在矩形路径上移动,因此它提供了一遍又一遍地绘制的矩形的视觉效果。 [老蛇游戏中的蛇运动]
我尝试使用CABasicAnimation制作动画,但事实上我无法实现任何目标。
答案 0 :(得分:2)
尝试此代码可能会有所帮助。
UIBezierPath *drawablePath = [UIBezierPath bezierPathWithRect:CGRectMake(100.0, 100.0, 150.0, 100.0)];
CAShapeLayer *squareLayer = [[CAShapeLayer alloc] init];
squareLayer.path = drawablePath.CGPath;
squareLayer.strokeColor = [UIColor redColor].CGColor;
squareLayer.lineWidth = 5.f;
squareLayer.fillColor = [UIColor clearColor].CGColor;
squareLayer.strokeEnd = 1.f;
//squareLayer.strokeEnd = 0.9; // this line use draw half line but some animation issue.
[self.view.layer addSublayer:squareLayer];
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
drawAnimation.fromValue = (id)[NSNumber numberWithFloat:0.10];
drawAnimation.toValue = (id)[NSNumber numberWithFloat:1.f];
drawAnimation.duration = 5.f;
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[squareLayer addAnimation:drawAnimation forKey:@"drawRectStroke"];
此代码用于绘制带动画的矩形。
答案 1 :(得分:1)
您必须为:strokeStart和strokeEnd设置动画,并使用CAAnimationGroup使它们同时发生。
我发现这个link做了类似但快速的事情。我认为这可能会有所帮助。
如果你不能这样做,我会尝试实施它。但我现在不能。
快乐的编码。
答案 2 :(得分:1)
let drawablePath = UIBezierPath(rect: CGRect(x: 100, y: 100, width: 150, height: 150))
let squareLayer = CAShapeLayer()
squareLayer.path = drawablePath.cgPath;
squareLayer.strokeColor = UIColor.red.cgColor;
squareLayer.lineWidth = 5;
squareLayer.fillColor = UIColor.clear.cgColor;
squareLayer.strokeEnd = 1;
//squareLayer.strokeEnd = 0.9; // this line use draw half line but some animation issue.
flowerView.layer.addSublayer(squareLayer)
let drawAnimation = CABasicAnimation(keyPath: "strokeEnd")
drawAnimation.fromValue = 0.1
drawAnimation.toValue = 1.0
drawAnimation.duration = 5
drawAnimation.timingFunction = CAMediaTimingFunction(name:.linear)
squareLayer.add(drawAnimation, forKey:"drawRectStroke")
这并不是对原始问题的真正答案,但这是Dixit Akabari的答案的Swift 5版本,它本身很有用,因为它演示了如何通过对strokeEnd进行动画来绘制UIBezierPath动画。