Search code examples
iosobjective-cwatchkit

Watchkit: How to loop an image from left to right in objective c?


So I have an image that I want to loop it by its origin x. Say the image is 300px in width. On the 42mm apple watch, it's 156px wide. I want to loop the image so that it look like a runway.

in my NSTimer interval:

UIImage*imgBg = [UIImage imageNamed:@"bgRun.png"];
int x = x-1;
[imgBg drawInRect:CGRectMake(x,0, 156,195)];

[groupBg setBackgroundImage:imgBg];

Few questions:

How to get an UIImage based on the origin x, y or frames in Watch OS? What function should I use? DrawInRect doesn't seem the correct function.

It doesn't seem like UIImageView works on watchkit because it's based on UIView.

Any advice would be grateful. Thank you.


Solution

  • In watchOS 2 you cannot animate objects like it happens under iOS. It means you just can set absolute values for an object position (WKInterfaceObjectHorizontalAlignment) by using a callback in animateWithDuration:animations of WKInterfaceController:

    For example infinite animation from the left to the right will be look like this:

    - (void) moveLeft {
        [self animateWithDuration:5.0 animations:^{
             [self.animatableObject setHorizontalAlignment:WKInterfaceObjectHorizontalAlignment.Left];
        }];
        [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(moveRight) userInfo:nil repeats:NO];
    }
    
    - (void) moveRight {
        [self animateWithDuration:5.0 animations:^{
            [self.animatableObject setHorizontalAlignment:WKInterfaceObjectHorizontalAlignment.Right];
        }];
        [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(moveLeft) userInfo:nil repeats:NO];
    }
    
    - (void) startInfiniteAnimation {
        [self moveLeft];
    }