1

我制作了一个程序,可以在屏幕顶部的随机 x 坐标处生成图像。然后图像下降到底部。但是,我想每隔几秒钟就不断地生成新的图像(同一图像的),这样就好像同一图像的这些副本不断地从顶部“下雨”。

我怎样才能让所有这些代码每 0.5 秒重复一次?

@implementation ViewController {

    UIImageView *_myImage;

}

- (void)viewDidLoad
{
    srand(time(NULL));e
    int random_x_coordinate = rand() % 286;
    CGRect myImageRect = CGRectMake(random_x_coordinate, 0.0f, 40.0f, 40.0f);
    UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
    [myImage setImage:[UIImage imageNamed:@"flake.png"]];
    myImage.opaque = YES;
    [self.view addSubview:myImage];
    _myImage = myImage;


    //FALLING BIRDS TIMER
    moveObjectTimer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(moveObject) userInfo:nil repeats:YES];


}
    //FALLING BIRDS MOVER
-(void) moveObject {        // + means down and the number next to it is how many pixels y moves down per each tick of the TIMER above
        _myImage.center = CGPointMake(_myImage.center.x, _myImage.center.y +1);
    }
4

1 回答 1

0

只需将动画循环放在您在计时器上调用的方法中,例如

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5
                                                      target:self
                                                    selector:@selector(animate)
                                                    userInfo:nil repeats:YES];
    [timer fire];
}

- (void)animate
{
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    view.backgroundColor = color;
    [self.view addSubview:view];

    [UIView animateWithDuration:1.0 animations:^{
        view.frame = CGRectMake(0, 200, 50, 50);
    }];
}

会给你从顶部连续下降的方块。请记住定期清理未使用的视图以避免内存问题。

于 2012-11-27T02:24:13.247 回答