2013-11-14 71 views
0

我使用核心动画(CAKeyframeAnimation)使用给定路径移动视图,同时显示路径(虚线)。 虽然沿着给定的路径对视图进行动画处理,但我希望它能够面对它所要的方向。 换句话说,我希望视图在移动时逐渐旋转。如何旋转已经随核心动画移动的视图?

经过一番研究,我发现使用keytimes和values可以用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); 
    } 

预先感谢您对您有所帮助,

回答

0

看一看CAKeyframeAnimation的rotationMode财产。这应该完成你正在做的事情。

此行添加到-animateView:方法,其中用于* pathAnimation CAKeyframeAnimation实例的属性正在被设置:

pathAnimation.rotationMode = kCAAnimationRotateAuto;

还有另一个设置值kCAAnimationRotateAutoReverse,它允许动画对象相对于路径切线保持反平行方向。

链接到苹果文档:CAKeyframeAnimation

+0

你可能要添加一个例子或附加说明。 – Mark