代码之家  ›  专栏  ›  技术社区  ›  user717452

为多次运行的iOS制作CABasicAnimation

  •  0
  • user717452  · 技术社区  · 7 年前

    我正在开发一个应用程序,使用简单的CABasicAnimation,一个图像在屏幕上“行走”的动画。我将其设置为在一段时间内走一定距离,然后停止,直到用户发出更多命令,它将再次继续走相同的距离和时间。我的问题是,在第一次之后,图像会停在它应该停的地方,但它不会继续行走,它会跳回原来的位置并重新开始。我以为我在原点上的设置是正确的,但我想不是。

    CABasicAnimation *hover = [CABasicAnimation animationWithKeyPath:@"position"];
        hover.fillMode = kCAFillModeForwards;
        hover.removedOnCompletion = NO;
        hover.additive = YES; // fromValue and toValue will be relative instead of absolute values
        hover.fromValue = [NSValue valueWithCGPoint:CGPointZero];
        hover.toValue = [NSValue valueWithCGPoint:CGPointMake(110.0, -50.0)]; // y increases downwards on iOS
        hover.autoreverses = FALSE; // Animate back to normal afterwards
        hover.duration = 10.0; // The duration for one part of the animation (0.2 up and 0.2 down)
        hover.repeatCount = 0; // The number of times the animation should repeat
        [theDude.layer addAnimation:hover forKey:@"myHoverAnimation"];
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   asanli SwiftDeveloper    7 年前

    您的from值设置为零,并且不会被更新。

    hover.fromValue = [NSValue valueWithCGPoint:CGPointZero];
    

    - (void)moveFromPoint:(CGPoint)fromPoint toPoint:(CGPoint)toPoint {
        CABasicAnimation *hover = [CABasicAnimation animationWithKeyPath:@"position"];
        hover.fillMode = kCAFillModeForwards;
        hover.removedOnCompletion = NO;
        hover.additive = YES; // fromValue and toValue will be relative instead of absolute values
        hover.fromValue = [NSValue valueWithCGPoint:fromPoint];
        hover.toValue = [NSValue valueWithCGPoint:toPoint]; // y increases downwards on iOS
        hover.autoreverses = FALSE; // Animate back to normal afterwards
        hover.duration = 10.0; // The duration for one part of the animation (0.2 up and 0.2 down)
        hover.repeatCount = 0; // The number of times the animation should repeat
        [theDude.layer addAnimation:hover forKey:@"myHoverAnimation"];
    }
    

    你可以通过每次用新的点调用这个函数来进一步移动这个家伙。

    [self moveFromPoint:CGPointZero toPoint:CGPointMake(110.0, -50.0)]
    
    [self moveFromPoint:CGPointMake(110.0, -50.0) toPoint:CGPointMake(160.0, -50.0)]
    

    编辑:

    我知道你每次都想以相同的比例移动那个家伙,但长度不同。

    @property (nonatomic) CGPoint oldPointOfTheGuy;
    

    并在前一个函数之后添加此新函数:

    - (void)moveByDistance:(CGFloat)distance {
        CGPoint newPointOfTheGuy = CGPointMake(self.oldPointOfTheGuy.x + 2.2*distance, self.oldPointOfTheGuy.y + distance);
        [self moveFromPoint:self.oldPointOfTheGuy toPoint:newPointOfTheGuy];
        self.oldPointOfTheGuy = newPointOfTheGuy;
    }
    

    并为视图中的家伙设置一个起点:

    self.oldPointOfTheGuy = CGPointMake(110.0, -50)
    

    从现在起,每次我们想移动他,我们都会称之为:

    [self moveByDistance:20];
    

    这个函数所做的是,因为它已经知道你的x/y比是2.2,它只是在你的旧y位置加20,在你的旧x位置加2.2*20。每次设置新位置时,旧位置都会更新。