Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image that loops as it slides horizontally across the screen to look like its scrolling infinitely

I would like to have a view controller that loops an image in the background to give the appearance of infinite scrolling. For example, If I were to use the image below, the left and right edges match up perfectly, and would be used to give an infinite scrolling appearance. Does anyone know how I might go about setting this up? I have done some research and am lost. Thank you all!

Infinite Scrolling Image

like image 228
Brandon Avatar asked Jan 21 '13 02:01

Brandon


1 Answers

I'd do it this way. EDIT Rather than leave it as an exercise for the reader, updated to show how to pan in either direction...

@property (nonatomic, assign) BOOL keepGoing;
@property (nonatomic, assign) BOOL panRight;
@property (nonatomic, strong) UIImageView *imageViewA;
@property (nonatomic, strong) UIImageView *imageViewB;

- (void)getReady {

    // init theImage
    UIImage *theImage = [UIImage imageNamed:@"theImage.png"];

    // get two copies of the image
    self.imageViewA = [[UIImageView alloc] initWithImage:theImage];
    self.imageViewB = [[UIImageView alloc] initWithImage:theImage];

    // place one in view, the other, off to the right (for right to left motion)
    NSInteger direction = (self.panRight)? 1 : -1;
    self.imageViewA.frame = self.view.bounds;
    self.imageViewB.frame = CGRectOffset(self.view.bounds, direction*self.imageViewA.bounds.size.width, 0.0);

    [self.view addSubview:self.imageViewA];
    [self.view addSubview:self.imageViewB];
    self.keepGoing = YES;
}

- (void)go {
    NSInteger direction = (self.panRight)? 1 : -1;
    CGFloat offsetX = -direction*self.imageViewA.bounds.size.width;

    [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.imageViewA.frame = CGRectOffset(self.imageViewA.frame, offsetX, 0);
        self.imageViewB.frame = CGRectOffset(self.imageViewB.frame, offsetX, 0);
    } completion:^(BOOL finished) {
        if (self.keepGoing) {
            // now B is where A began, so swap them and reposition B
            UIImageView *temp = self.imageViewA;
            self.imageViewA  = self.imageViewB;
            self.imageViewB = temp;
            self.imageViewB.frame = CGRectOffset(self.view.bounds, direction*self.view.bounds.size.width, 0.0);
            // recursive call, but we don't want to wind up the stack
            [self performSelector:@selector(go) withObject:nil afterDelay:0.0];
        }
    }];
}

To make it go, set the panRight property, then call [self getReady]; and [self go];.

It will run mostly asynch. To make it stop, set self.keepGoing = NO;.

like image 124
danh Avatar answered Oct 20 '22 00:10

danh