xcode iphone球动画

时间:2011-04-20 08:59:28

标签: iphone xcode animation timer coordinates

我想要做的是每隔十秒钟在屏幕外创建一个球,当它被创建时,它会移动到屏幕的中心。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

- (void)viewDidLoad {
    [super viewDidLoad];

    myBallImage = [[UIImage imageNamed:@"ball.png"] retain];
    myTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(addBallToScreen) userInfo:nil repeats:YES];
}
- (void)viewDidUnload {
    [myBallImage release];
    [myTimer invalidate];
}

- (void)addBallToScreen {
    //Create the imageView
    UIImageView *imageView = [[UIImageView alloc] initWithImage:myBallImage];
    imageView.transform = CGAffineTransformMakeTranslation(1000, 1000);
    [self.view addSubview:imageView];
    [imageView release];

    //Animate the image view
    [UIView beginAnimations:nil context:nil];
    imageView.transform = CGAffineTransformMakeTranslation(50, 50);
    [UIView commitAnimations];
}

答案 1 :(得分:0)

在你的视图控制器中为你的球设置一个UIImageView属性,构造球并确保它的起始位置离开creen的可视区域,然后使用NSTimer,它每10秒触发一次,这是一种动画你的方法球越过屏幕到达中心。

-(void)viewDidLoad{
    NSTimer *ballTimer = [NSTimer timerWithTimeInterval:10.0  
                                                 target:self 
                                               selector:@selector(moveBall) 
                                               userInfo:nil 
                                                repeats:YES];

    [[NSRunLoop mainRunLoop] addTimer:ballTimer forMode:NSRunLoopCommonModes];

    myBall = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MyBallImageFile.png"]];
    myBall.center = CGPointMake(320/2, [self randNumBetween:-50:-100]);
    [self.view addSubview:myBall];
}

-(void)moveBall{
    myBall.center = CGPointMake(320/2, [self randNumBetween:-50:-100]);
    [UIView animateWithDuration:5.0 animations:^{
        myBall.center = CGPointMake(320/2, 480/2);
    }];
}

<强> ---------- ------------ EDIT

- (CGFloat)randNumBetween:(CGFloat) min :(CGFloat) max{
    CGFloat difference = max - min;
    return (((CGFloat) rand()/(CGFloat)RAND_MAX) * difference) + min;
}