我使用核心动画(CAKeyframeAnimation)使用给定路径移动视图,同时显示路径(虚线)。在沿给定路径为视图设置动画时,我希望它面向它要去的方向。换句话说,我希望视图在移动时逐渐旋转。
经过一些研究,我发现可以使用 CAKeyFrameAnimation 使用关键时间和值来做到这一点,但没有成功。我不知道如何实现它。
由于我还是 IOS 编程的新手,我不知道是否有另一种(更好的?)方法来制作这种动画。
这是我使用的代码:
- (CGMutablePathRef) getPathFromPoints:(NSMutableArray*)points {
CGMutablePathRef path = CGPathCreateMutable();
CGPoint p = [points[0] CGPointValue];
CGPathMoveToPoint(path, NULL, p.x, p.y);
for (int i = 1; i < points.count; ++i) {
p = [points[i] CGPointValue];
CGPathAddLineToPoint(path, NULL, p.x, p.y);
}
return path;
}
- (void)animateView:(UIView*)view
withPoints:(NSMutableArray*)points
withFillMode:(NSString*)fillMode
withDuration:(int)duration
withRepeatCount:(int)repeat
withSpeed:(int)speed
withDashed:(BOOL)dashed{
CGMutablePathRef path = [self getPathFromPoints:points];
if (dashed) {
CAShapeLayer* pathLayer = [CAShapeLayer layer];
pathLayer.frame = view.superview.layer.bounds;
pathLayer.bounds = view.superview.layer.bounds;
pathLayer.geometryFlipped = NO;
pathLayer.path = path;
pathLayer.strokeColor = [[UIColor blackColor] CGColor];
pathLayer.fillColor = nil;
pathLayer.lineWidth = 10.0f;
pathLayer.lineJoin = kCALineJoinBevel;
[pathLayer setLineDashPattern:[[NSArray alloc] initWithObjects:
[NSNumber numberWithInt:15],
[NSNumber numberWithInt:15],
nil]];
[view.superview.layer addSublayer:pathLayer];
CABasicAnimation *dottedAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
dottedAnimation.duration = duration;
dottedAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
dottedAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[pathLayer addAnimation:dottedAnimation forKey:@"strokeEnd"];
[view.superview bringSubviewToFront:view];
}
CAKeyframeAnimation* pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
pathAnimation.calculationMode = kCAAnimationPaced;
pathAnimation.fillMode = fillMode;
pathAnimation.duration = duration;
pathAnimation.repeatCount = repeat;
pathAnimation.speed = speed;
pathAnimation.path = path;
[view.layer addAnimation:pathAnimation forKey:_myAnimationKey];
CGPoint p = [[points lastObject] CGPointValue];
view.layer.position = CGPointMake(p.x, p.y);
}
提前感谢您的帮助,