【问题标题】:Animating a group of UIView subviews continuously连续动画一组 UIView 子视图
【发布时间】:2015-04-15 18:55:45
【问题描述】:

我试图在我的应用中显示车辆在道路上的运动。为此,我让我的车辆保持静止,并不断地从上到下移动道路上的车道以创造效果。车道作为子视图添加到 roadView,我正在尝试为 roadView 中的所有子视图设置动画,如下面的代码所示。

我面临的问题是最接近底部的车道与开始时顶部的车道相比以更快的速度移动,尽管我是根据恒定速度计算持续时间。

-(void)animateLanes {

for (UIView *laneView in [self.roadView subviews]) {

    if (laneView.tag < 10) {
        float distance = self.view.frame.size.height - CGRectGetMaxY(laneView.frame);
        float duration = distance/10;

        [UIView animateWithDuration:duration animations:^{

            laneView.frame = CGRectMake(laneView.frame.origin.x, self.view.frame.size.height+laneView.frame.size.height, laneView.frame.size.width, laneView.frame.size.height);


        } completion:^(BOOL finished) {

            laneView.frame = CGRectMake(self.roadView.frame.size.width/2 - 10, -laneView.frame.size.height, 20, 40);
            [self nextStep:laneView];
        }];
    }
}
}

-(void) nextStep:(UIView *) laneView{

float distance = self.view.frame.size.height - CGRectGetMaxY(laneView.frame);
float duration = distance/10;

[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionRepeat animations:^{

    laneView.frame = CGRectMake(laneView.frame.origin.x, self.view.frame.size.height+laneView.frame.size.height, laneView.frame.size.width, laneView.frame.size.height);
} completion:^(BOOL finished) {
    laneView.frame = CGRectMake(self.roadView.frame.size.width/2 - 10, -laneView.frame.size.height, 20, 40);

}];
}

【问题讨论】:

  • 这听起来不太适合视图动画。考虑学习游戏编程技术。

标签: ios objective-c animation uiview uiviewanimation


【解决方案1】:

我肯定会研究 SpriteKit 来做这种事情。 SKScene 中的更新循环可让您确保一切运行顺利。

但是,如果您这样做,则不必进行所有这些 UIView 动画调用。这样做:

//calculate duration and distance first, then:
[UIView animateWithDuration:duration animations:^{    

    for (UIView *laneView in [self.roadView subviews]) {
        laneView.frame = CGRectMake(laneView.frame.origin.x, self.view.frame.size.height+laneView.frame.size.height, laneView.frame.size.width, laneView.frame.size.height);
    }


} completion:^(BOOL finished) {
    for (UIView *laneView in [self.roadView subviews]) {
        laneView.frame = CGRectMake(self.roadView.frame.size.width/2 - 10, -laneView.frame.size.height, 20, 40);
        [self nextStep:laneView];
    }
}];

虽然我不建议这样做。使用游戏库,即 SpriteKit,因为它易于集成和简单。

【讨论】:

  • 关于你上面分享的sn-p,虽然我还没有尝试过,但我觉得我无法先计算for循环之外的持续时间,因为每个车道视图都会有所不同。不过我会考虑研究 sprite kit 来实现这一点。
【解决方案2】:

SpriteKit 更适合这种类型的任务,IMO。逻辑类似,对象属于 SKScene 实例,该实例有一个方便的 update 方法,非常适合您的目标循环效果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多