views:

248

answers:

4

What is the best or recommended technique for animating PNG Sequences.
Heres what I've learned:

Do it Manually
Using MutableArrays containing Strings, you can animate a UIImageView with a timer which increments an index number

UIImage - animation methods
This works, the only problem is to find if an image has completed its animation, you have to check the isAnimating BOOL, and to do that you need a timer.

What is the best and recommended?

Looking to do Oldschool game sprite animations, ie:

Idle Animation
Attack Animation
Walk Animation
ect...

Let me know if any one has something.

@lessfame

A: 

start here

ohho
A: 

It depends on how you are going to use the sprites. If you just need a simple looping sprite then the UIImage method is great. If you want more granular control then you will be happier loading the images into an array and cycling them using a NSTimer to handle the timing. Personally I use the array method most often because it leaves me more options in the future (like detecting when animations have completed). One more suggestion would be to check out the cocos2d project. Its sprite is alot more powerful than either of these suggestions.

Jason Webb
+1  A: 

Easiest way is to use Core Animation layers to do sprite animation:

  • Make a 'multi-cell' image strip (could be PNG or JPG) of all the various moves for the sprite. Make each 'cell' be a fixed height or width.

  • Put the image in a UIImageView.

  • Take the CALayer of the view, and adjust the contentsRect property of the layer. This acts as a clipping rectangle for the sprite. To animate sprite all you have to do is move the contentsRect over to the next cell position in the image strip.

Something like this will do it (assuming you've already calculated the newSpritePosition.

  [CATransaction begin];
  [CATransaction setDisableActions:YES];
  spriteLayer.contentsRect = newSpritePosition;
  [CATransaction commit];

(If you don't do the second line, then you'll get a default slide animation instead of a 'jump' to the next state.)

With this technique you can rotate through all the frames of the sprite -- much like a flipbook. CALAyer transactions are optimized so you should get pretty fast frame rates. You can set an animationDidStop completion handler to move to the next state of the sprite or loop back to the beginning frame.

Ramin
+1  A: 

Example to animate arrows

UIImage* img1 = [UIImage imageNamed:@"fleche1.png"]; UIImage* img2 = [UIImage imageNamed:@"fleche2.png"];

    NSArray *images = [NSArray arrayWithObjects:img1,img2, nil];
    UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 160.0, 160.0)];
    [imageView setAnimationImages:images];
    [imageView setAnimationRepeatCount:100];
    [imageView setAnimationDuration:3.0];
    imageView.center = myView.center;


    [imageView startAnimating];
    [myView addSubview:imageView];
    [imageView release];
Kirill SIMAGIN