This question already has an answer here:
Moving an object randomly around the screen

(1个答案)


7年前关闭。




因此,我尝试使用一些UIViews做长时间运行的动画。基本上,我要完成的工作是获取一个正方形的子视图,并使其在背景中的屏幕周围随机浮动(就像叶子漂浮在池塘上一样)。我希望使用常规动画来做到这一点,但到目前为止,即使将选项设置为从当前位置开始,动画还是会停止播放。有人知道这样做的简单方法吗?

我已经看到Moving an object randomly around the screen了,但是那不是由于递归而最终导致堆栈溢出吗?

另外,我在问如何在没有添加库/框架的情况下执行此操作。

谢谢!

最佳答案

我为您编写了以下代码:

- (CGFloat) distanceBetweenTwoPoints: (CGPoint) point1 : (CGPoint) point2 {
    CGFloat dx = point2.x - point1.x;
    CGFloat dy = point2.y - point1.y;
    return sqrt(dx*dx + dy*dy );
}

#define kMovingSpeed 25 //pixel per second
- (void) floatView : (id) view_{
    UIView *view = (UIView *)view_;
    CGPoint viewCenter = view.center;
    CGPoint nextCenter = CGPointMake(arc4random() % 320, arc4random() % (([self.view bounds].size.height > 480)?568:460));//or chech for orientation as well
    if (CGPointEqualToPoint(viewCenter, nextCenter))
        [self floatView:view];

    float distance = [self distanceBetweenTwoPoints:viewCenter :nextCenter];
    double time = distance / kMovingSpeed;

    [UIView animateWithDuration:time
                     animations:^{
                         [view setCenter:nextCenter];
                     }
                     completion:^(BOOL finished) {
                         [self floatView:view];
                     }];
}

10-02 01:11