2012-11-27 36 views
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); 
    } 
+0

檢查您是否可以使用動畫來創建秋季效果。您可能需要在for循環中創建UIImageView,以便爲多個圖像執行此操作,然後將其存儲在數組中或進行動畫處理。 – iDev

回答

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); 
    }]; 
} 

會給你方塊從上落下,持續。請記得定期清理未使用的視圖以避免內存問題。

+0

非常感謝這個參考代碼。不過,我相信我必須逐步移動每個對象(而不是動畫),因爲這個應用程序將會是一個需要隨時瞭解每個圖像位置的遊戲 - 所以我不會認爲我可以使用動畫循環。 – user1824518