我有一个 21 帧的菜单背景动画。我在 View 的 viewDidLoad 方法中使用以下代码将它们加载到内存中。
NSMutableArray *menuanimationImages = [[NSMutableArray alloc] init];
for( int aniCount = 0; aniCount < 21; aniCount++ )
{
NSString *fileLocation = [[NSBundle mainBundle] pathForResource: [NSString stringWithFormat: @"bg%i", aniCount + 1] ofType: @"png"];
NSData *imageData = [NSData dataWithContentsOfFile: fileLocation];
[menuanimationImages addObject: [UIImage imageWithData:imageData]];
}
settingsBackground.animationImages = menuanimationImages;
不幸的是,做 [settingsBackground startAnimating];在 viewDidLoad 方法中不起作用。有没有什么方法可以预加载动画,以便在第一次运行时不会有 1-3 秒的延迟?
最佳答案
我通常不建议使用 imageNamed 并依赖内置的缓存机制。如果你搜索,你会发现很多关于这个的讨论,但它也不一定会预渲染你的图像。
我使用以下代码预加载和预渲染图像,因此在第一次制作动画时没有延迟。
NSMutableArray *menuanimationImages = [[NSMutableArray alloc] init];
for (int aniCount = 1; aniCount < 21; aniCount++) {
NSString *fileLocation = [[NSBundle mainBundle] pathForResource: [NSString stringWithFormat: @"bg%i", aniCount + 1] ofType: @"png"];
// here is the code to pre-render the image
UIImage *frameImage = [UIImage imageWithContentsOfFile: fileLocation];
UIGraphicsBeginImageContext(frameImage.size);
CGRect rect = CGRectMake(0, 0, frameImage.size.width, frameImage.size.height);
[frameImage drawInRect:rect];
UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[menuanimationImages addObject:renderedImage];
}
settingsBackground.animationImages = menuanimationImages;
关于iphone - 执行 startAnimating 时的 UIImageView 动画延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7863061/