简体   繁体   中英

iphone development: animation with NSTimer

I wrote the code below to make move an image from the top to the button by using NSTimer. However when I run it I cannot have the images separately. Basically, the image leaves trace. what I want is to have the image frame by frame it is moving. What am I missing?

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

}

edit: I don't want to use animation. Because later on I need to use collision detection and it is not possible to control the coordinates of the animations.

You are allocating and adding subView every time to the self. When are you removing the ImageView to disappear the Previous ImageView. So try removing the image before allocating. Try like this

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

Do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM