2012-08-27 35 views
0

我写了下面的代码,使用NSTimer从顶部移动到按钮的图像。但是,当我运行它时,我无法单独获取图像。基本上,图像留下痕迹。我想要的是让图像逐帧移动。我错过了什么?iphone开发:动画与NSTimer

-(void)printOut:(NSTimer*)timer1; 
{ 

    image = [[UIImageView alloc] initWithFrame:CGRectMake(50, -50+m, 50, 50)]; 
    [image setImage:[UIImage imageNamed:[NSString stringWithFormat:@"image.png"]]]; 

    CGRect oldFrame = image.frame; 
    image.frame = CGRectMake(oldFrame.origin.x+5, oldFrame.origin.y, oldFrame.size.width, oldFrame.size.height); 

    [self.view addSubview:image]; 

    m++; 
    if (m == 1000) { 
     [timer1 invalidate]; 
    } 

} 

编辑:我不想使用动画。因为稍后我需要使用碰撞检测,并且不可能控制动画的坐标。

+0

我无法理解你的query..canü请 – Rajneesh071

+0

@ Rajneesh071好吧,当我运行这段代码的图像从屏幕顶部出现,并开始移动,但它不是一帧帧发生。我的意思是当新框架出现时,前一帧不会消失。希望它很清楚:/ – death7eater

+0

UIImageView * image = [[UIImageView alloc] initWithFrame:CGRectMake(50,-50 + m,50,50)]; [image setImage:[UIImage imageNamed:[NSString stringWithFormat:@“image.png”]]]; [self.view addSubview:image]; – Rajneesh071

回答

3

您分配和自我每次添加子视图。何时删除ImageView以消除Previous ImageView。所以尝试在分配之前删除图像。试着这样

-(void)printOut:(NSTimer*)timer1; 
{ 
[image removeFromSuperview]; 
image = nil; 
image = [[UIImageView alloc] initWithFrame:CGRectMake(50, -50+m, 50, 50)]; 
[image setImage:[UIImage imageNamed:[NSString stringWithFormat:@"image.png"]]]; 

CGRect oldFrame = image.frame; 
image.frame = CGRectMake(oldFrame.origin.x+5, oldFrame.origin.y, oldFrame.size.width, oldFrame.size.height); 

[self.view addSubview:image]; 

m++; 
if (m == 1000) { 
    [timer1 invalidate]; 
} 
} 
2

这样做:

image.frame = (top frame here) 

[UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{ 
//change time duration according to requirement 
// animate it to the bottom of view 
image.frame = (bottom frame here) 
} completion:^(BOOL finished){ 
// if you want to do something once the animation finishes, put it here 
}]; 
+0

嗯,我很抱歉,但事情是我不想使用动画。因为稍后我需要使用碰撞检测,并且不可能控制动画的坐标。 – death7eater