我不确定我的标题是否完全正确,但我不确定我的问题到底出在哪里。
我需要从 spritesheet 加载 UIImage 数组,然后将其用作 UIImageView 中的动画。
spritesheet 是使用 TexturePacker 生成的,TexturePacker 会生成巨大的图集 (2048x2048) 和带有 sprite 描述的 json。
到现在为止,我让它正常工作,甚至在 0.5-0.8 秒内加载 100 帧,这让我非常满意。
现在的问题是我需要从 Documents 文件夹中加载 spritesheets(它们已下载,因此无法集成到应用程序中),因此我必须UIImage imageWithContentsOfFile
使用UIImage imagenamed
. 这使我的加载时间增加了 5-15 秒,具体取决于动画中的帧数。我猜问题是因为图像没有被缓存,正在为每一帧加载它,但我不明白为什么
这是代码:
// With this line, perfect
//UIImage *atlas = [UIImage imageNamed:@"media/spritesheets/default-pro7@2x.png"];
// But with this one, incredibly looooong loading times
UIImage *atlas = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"media/spritesheets/default-pro7@2x" ofType:@"png"]];
CGImageRef atlasCGI = [atlas CGImage];
for( NSDictionary* dict in frames) {
NSDictionary *frame = [dict objectForKey:@"frame"];
int x = [[frame objectForKey:@"x"] intValue];
int y = [[frame objectForKey:@"y"] intValue];
int width = [[frame objectForKey:@"w"] intValue];
int height = [[frame objectForKey:@"h"] intValue];
NSDictionary *spriteSize = [dict objectForKey:@"spriteSourceSize"];
int realx = [[spriteSize objectForKey:@"x"] intValue];
NSDictionary *size = [dict objectForKey:@"sourceSize"];
int realWidth = [[size objectForKey:@"w"] intValue];
int realHeight = [[size objectForKey:@"h"] intValue];
//Initialize the canvas size!
canvasSize = CGSizeMake(realWidth, realHeight);
bitmapBytesPerRow = (canvasSize.width * 4);
bitmapByteCount = (bitmapBytesPerRow * canvasSize.height);
bitmapData = malloc( bitmapByteCount );
//Create the context
context = CGBitmapContextCreate(bitmapData, canvasSize.width, canvasSize.height, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
// Clear background
CGContextClearRect(context,CGRectMake(0.0f,0.0f,canvasSize.width,canvasSize.height));
// Get spriteRect
CGRect cropRect = CGRectMake(x, y, width, height);
CGImageRef imageRef = CGImageCreateWithImageInRect(atlasCGI, cropRect);
//Draw the image into the bitmap context
CGContextDrawImage(context, CGRectMake(realx, 0, width, height), imageRef);
//Get the result image
resultImage = CGBitmapContextCreateImage(context);
UIImage *result = result = [UIImage imageWithCGImage:resultImage];
[images addObject:result];
//Cleanup
free(bitmapData);
CGImageRelease(resultImage);
CGImageRelease(imageRef);
}
我什至可以尝试一个上传系统分析器会话,它显示在哪里加载了这么多时间