在 iPhone 应用程序中预加载图像?
我有一系列需要在短时间内显示的图像(PNG 序列)。总共有31个PNG,每个文件大小约为45KB。我已经使用以下代码加载了它们:
imgArray = [[NSMutableArray alloc] init];
for(int i = 0; i <= 30; i++) {
NSString * filename = [NSString stringWithFormat:@"img_000%.2d.png", i];
UIImage *temp = [UIImage imageNamed:filename];
[imgArray addObject:temp];
[temp release];
temp = nil;
}
我使用以下代码来显示图像:
CGImageRef image = [(UIImage *)[imgArray objectAtIndex:imgFrame] CGImage];
imgLayer.contents = (id)image;
if(imgFrame < 29) {
imgFrame++;
} else {
imgFrame = 0;
imgLayer.hidden = TRUE;
[imgTimer invalidate];
}
其中 imgLayer 是 CALayer
。 (imgTimer是一个重复定时器,间隔为0.03s)
但是我发现当我第一次调用图像时,它非常滞后。除了第一个外观之外,其他外观都没有问题。
与预加载图像有关吗?或者我的图像文件太大?
I have a sequence of images needed to display in a short time (PNG sequence). There are totally 31 PNGs in total, each with file size about 45KB. I have already loaded them with the following codes:
imgArray = [[NSMutableArray alloc] init];
for(int i = 0; i <= 30; i++) {
NSString * filename = [NSString stringWithFormat:@"img_000%.2d.png", i];
UIImage *temp = [UIImage imageNamed:filename];
[imgArray addObject:temp];
[temp release];
temp = nil;
}
I use the following codes for displaying the images:
CGImageRef image = [(UIImage *)[imgArray objectAtIndex:imgFrame] CGImage];
imgLayer.contents = (id)image;
if(imgFrame < 29) {
imgFrame++;
} else {
imgFrame = 0;
imgLayer.hidden = TRUE;
[imgTimer invalidate];
}
where imgLayer is a CALayer
. (imgTimer is a repeating timer with interval 0.03s)
But I found that when I call the images out, it is very laggy at the first time. Except the 1st appearance, other appearance has no problem.
Is it related to preloading images? Or are my images too big in file size?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果没有分析数据,很难判断滞后的原因。但这里有一个技巧可能会有所帮助:将所有图像合并到一个大文件中。尝试将其设为矩形(在您的情况下可能是 6x6 或 4*8)。然后加载该单个文件并裁剪每个图像以供显示(即创建一个以图块大小显示的图像,并将大图像中的一个图块复制到显示图像中)。
The reason for your lags are hard to tell without profiling data. But here is a trick that might help: Join all your images into one large file. Try to make it rectangular (maybe 6x6 in your case or 4*8). Then load this single file and crop each image out for display (i.e. create an image for display with the size of a tile and copy one tile from the big image after the other into the display image).
图像在使用和显示时加载。
如果您使用 Instruments 中的时间分析器,您将会遇到延迟。如果您随后放大到该滞后并查看导致其的原因,您通常会看到“copyImageBlockSetPNG”是在“inflate”之前花费时间的函数。
您必须找到一种方法来创建图像并在需要它们之前强制加载它们。这显然是另一个故事了。
Images are loaded when they are used and displayed.
If you use the time profiler in Instruments, you will the lag you're experiencing. If you then zoom to that lag and look at what is causing it, you will usually see that "copyImageBlockSetPNG" is the function taking time, right before "inflate".
What you must find a way to do is create your images and force load them before you need them. That's another story apparently.