gpt4 book ai didi

ios - 使 iOS 的 CABasicAnimation 运行多次

转载 作者:行者123 更新时间:2023-11-29 00:12:29 26 4
gpt4 key购买 nike

我正在构建一个应用程序,该应用程序将使用简单的 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"];

最佳答案

您的 from 值设置为零且未更新。

hover.fromValue = [NSValue valueWithCGPoint:CGPointZero];

您每次都必须使用您的 to 值更新此值。

在这里,我将您的代码放在一个函数中,您可以在其中更新起点和终点。

- (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)]

编辑:

我看到您想以相同的比例移动这个人,但每次移动的长度不同。

在@interface 之后添加这个变量:

@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;
}

然后在你的 viewDidLoad 中为这个人设置一个起点:

self.oldPointOfTheGuy = CGPointMake(110.0, -50)

现在我们已经将这个人的旧位置设置为我们知道他第一次生成的位置。

从现在开始,每次我们要移动他时,我们都会这样调用:

[self moveByDistance:20];

这个函数的作用是,因为它已经知道你的 x/y 比率是 2.2,所以它只是将 20 添加到你的旧 y 位置并将 2.2 * 20 添加到你的旧 x 位置。每次设置新位置时,都会更新旧位置。

希望这对您有所帮助。

关于ios - 使 iOS 的 CABasicAnimation 运行多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46066324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com