简体   繁体   中英

Move image from left to right

In my application after the view load, an image should appear from left to right. I am writing this code in in viewdidload or viewwillappear :

       UIImage *image = [UIImage imageNamed:@"PG05(REV).jpg"];
       UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
       for (int i=-1024; i<=0; i++) {
               NSLog(@"i: %d",i);
       sleep(5);
       imageView.frame = CGRectMake(i,0, 1024, 768);
               NSLog(@"done");
       [self.view addSubview:imageView];

       }
       [imageView release];

But problem is that, before loading view it executes the above code than loads the view, so that it seems that view loaded and a static image is there. But my requirement is that first view load completely then image should display from left to right.

Please help me out.

First of all, you should not call the -(void)addSubview: inside your for loop. You just need to call it once. Secondly, if you want to animate your imageView from left to right, UIView class provides great functionalities for this using blocks.

Your code should look like this :

UIImage *image = [UIImage imageNamed:@"PG05(REV).jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(-1024, 0, 1024, 768);
[self.view addSubview:imageView];
[imageView release]; //Your imageView is now retained by self.view

//Animation
[UIView animateWithDuration:2.0
                 animations:^(void) {
                    imageView.frame = CGRectMake(0, 0, 1024, 768);
                 }];

The animateWithDuration: method will handle the animation timer for you, just set the duration argument according to your needs.

You can use a function and call it using timer method.

timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(moveImage) userInfo:nil repeats:NO];

-(void)moveImage
{
//Your condition
}

You shouldn't do addSubView: more than once, before the loop. Also, you should use animations for this and not a sleep loop.

Example:

imageView.frame = CGRectMake(-1024,0, 1024, 768);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 5];
imageView.frame = CGRectMake(0,0, 1024, 768);
[UIView commitAnimations];

This is a job for UIView animations.

Put your imageView down at -1024 left, then go:

[imageView animateWithDuration:5 animations:^{
    [imageView.frame = CGRectMake(0,0, 1024, 768)];
}];

Ta-da! A five second animation of your image sliding to the right.

Check out the animation methods of UIView (of which UIImageView is a subclass): http://developer.apple.com/library/ios/#documentation/uikit/reference/UIView_Class/UIView/UIView.html

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