Hi!
I have a set of several png files. And I want to make animation from them - just change one to another after specific time period.
So I tried to implement this using layers:
First of all I made a layer for each frame and sorted them in depth:
then I implemented a method that increases zPosition on each layer by 1. First layer goes to back:
calling this method when user touches the screen
It works! But now I need animation to function all by itself without touches on screen. So in viewDidAppear I perform calling of this method in infinite loop in another thread:
But such animation does not function. Nothing changes on screen. I even tried to add [self.view.layer setNeedsDisplay] in infinite loop.
Does anybody know what the problem is? Or there is maybe less complicated way to create animation from set of separatte images?
I have a set of several png files. And I want to make animation from them - just change one to another after specific time period.
So I tried to implement this using layers:
First of all I made a layer for each frame and sorted them in depth:
Code:
- (void)viewDidLoad {
[super viewDidLoad];
for(NSUInteger k = 1; k <= 7; k++) {
CALayer *frame = [CALayer layer];
frame.bounds = CGRectMake(0.0f, 0.0f, 100.0f, 100.0f);
frame.position = CGPointMake(160.0f - 20.0f, 240.0f - 20.0f);
frame.zPosition = -k;
NSString *fileName = [NSString stringWithFormat:@"%d", k];
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:@"png"]];
frame.contents = [image CGImage];
[self.view.layer addSublayer:frame];
}
}
then I implemented a method that increases zPosition on each layer by 1. First layer goes to back:
Code:
- (void)nextFrame {
NSArray *layers = self.view.layer.sublayers;
CALayer *firstLayer = (CALayer *)[layers objectAtIndex:0];
[firstLayer removeFromSuperlayer];
CALayer *lastLayer = (CALayer *)[layers objectAtIndex:layers.count];
firstLayer.zPosition = lastLayer.zPosition;
CALayer *layer;
for(layer in layers)
layer.zPosition ++;
[self.view.layer insertSublayer:firstLayer below:lastLayer];
}
calling this method when user touches the screen
Code:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self nextFrame];
}
It works! But now I need animation to function all by itself without touches on screen. So in viewDidAppear I perform calling of this method in infinite loop in another thread:
Code:
- (void)viewDidAppear:(BOOL)animated {
[ NSThread detachNewThreadSelector: @selector(myThreadedMethod) toTarget: self withObject: nil ];
}
- (void)myThreadedMethod {
NSAutoreleasePool *pool = [ [ NSAutoreleasePool alloc ] init ];
while(YES) {
[self nextFrame];
sleep(1);
}
[ pool release ];
}
But such animation does not function. Nothing changes on screen. I even tried to add [self.view.layer setNeedsDisplay] in infinite loop.
Does anybody know what the problem is? Or there is maybe less complicated way to create animation from set of separatte images?