0

我编写了下面的代码,使用 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];
    }

}

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

4

2 回答 2

3

您每次都在为自己分配和添加 subView。什么时候删除 ImageView 以使以前的 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];
}
}
于 2012-08-27T10:12:47.083 回答
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
}];
于 2012-08-27T09:34:11.577 回答