我编写了下面的代码,使用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 :(得分:3)
每次为自己分配和添加子视图。您何时删除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];
}
}
答案 1 :(得分: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
}];