iphone - 执行 startAnimating 时的 UIImageView 动画延迟

标签 iphone objective-c ios ipad uiimageview

我有一个 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/

相关文章:

iphone - 放大和缩小 UIImage

ios - 在 ios 上调用 dlopen

ios - uiviewcontroller dealloc时如何在 objective-c 中触发 block 事件

ios - UILabel 未使用 UITableViewCell 自定义类 Swift 进行更新

ios - Combine Future Publisher 没有被释放

iphone - UIImagePickerController 不释放它占用的内存

iphone - 如何在 subview 中访问ViewController的数据?

ios - 摆脱表格 View 单元格中的重叠图像

objective-c - 核心图标题路径错误

ios - 谓词抛出异常