Obj-C大量图片构成动画的实现(一)

  • Post author:
  • Post category:其他


准备实现一个由大量图片(帧)构成动画的方案,查询良久,写个总结。

主要方案有3个,

1、通过unity 3d来做3d的动画模型出来,然后进行贴图的操作,该方案没有深究。

2、Cocos2d的库来做动画,这种动画方式又分为两个方案。

1)通过TP等来形成动画帧,这需要对动画帧图片进行一个预处理。生成对应的plist文件。缺点是如果过多的动画帧(比如100个图)集结在一个plist描述里面载入会非常慢,即使采用RGBA4444进行一个优化也较慢。

动画实现的代码主要是:

[[CCSpriteFrameCachesharedSpriteFrameCache] addSpriteFramesWithFile: @"xxx.plist"];
CCSpriteBatchNode * spirteSheet = [CCSpriteBatchNode batchNodeWithFile:@"xxx.png"];
[self addChild:spirteSheet];

NSMutableArray *animFrames = [NSMutableArray array];
for(int i =1; i <=8; ++i) {
  [animFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"xxx%d.png", i]]]; 
}
CCAnimation * anim = [CCAnimation animationWithFrames:animFrames delay:0.1f];
CCAction * action = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:anim restoreOriginalFrame:NO]];

2) 对每一帧进行一个单独的图片载入和缓存,这个同样存在过多图片缓存的问题,iTouch上每次载入大概40张左右的帧图片(320*480)即会出现错误。不过少量的帧动画仍然是不错的选择。

对应的动画实现代码:

+ (CCAnimation *) animationWithAllFile:(NSString *)imageName frameCount:(int)frameCount delay:(float)delay{
NSMutableArray * frames = [NSMutableArray arrayWithCapacity:frameCount];
for (int i = 0; i < frameCount; ++i) {
NSString * file = [NSString stringWithFormat:@"%@%i.jpg",imageName,i];
CCTexture2D * texture = [[CCTextureCache sharedTextureCache] addImage:file];

CGSize texSize = texture.contentSizeInPixels;
CGRect texRect = CGRectMake(0, 0, texSize.width, texSize.height);
CCSpriteFrame * frame = [CCSpriteFrame frameWithTexture:texture rect:texRect];
[frames addObject:frame];
}
return [CCAnimation animationWithFrames:frames delay:delay];
}

3、直接用UIImageView的自带动画来实现,本来以为这种方式可能太弱了,没想到尝试的结果颇为满意。

连续播放帧图片达80张依然很流畅,内部缓存方式就不深究了。具体实现方式如下:

NSMutableArray * animateArray = [[NSMutableArray alloc] initWithCapacity:80];
for (int i = 0; i < 78; ++i) {
NSString * file = [NSString stringWithFormat:@"%@%i",@"eating_",i];
[animateArray addObject:[UIImage imageWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:file ofType:@"jpg"]]];
}
animImage.animationImages = animateArray;
animImage.animationDuration = 3.0;
animImage.animationRepeatCount = 0;

转载于:https://www.cnblogs.com/andywordsworth/archive/2012/03/25/2416634.html