UIImageView动画预加载



几天来,我一直在努力寻找最有效的解决方案,将图像数组加载到.animationImages属性中,并能够随时更改该数组。以下是场景:-我有一个UIImageView-根据用户输入(手机移动、陀螺仪),我会加载一组特定的图像来制作动画。-在用户输入(触摸)时播放加载的动画。

现在,使用"NSThreaddetachNewThreadSelector"将图像数组加载到另一个线程上,该"NSThread detachNewThreadSelector"是从使用initWithData在gyroHandler上运行的块中调用的(仅在某些情况下)。其他的启动方法完全失败了。

现在的问题是,当我第一次触摸(因为当前动画已经加载)并触发动画时,整个事情会冻结为aprox。一秒钟,然后播放动画。如果我再次触摸,它会成功播放动画,不会延迟/冻结。

现在我在某个地方读动画背景。。。我尝试使用:

[imgAnimationKey performSelectorInBackground:@selector(startAnimating) withObject:nil];

但结果是一样的。

我的数组有19个图像,很可能永远都是一样的。问题是我可能有更多的5+动画可以播放,这就是为什么我没有多个UIImageViews。

有人知道如何预加载图像并避免第一次播放时的延迟吗?或者我可以让动画在不同的线程中运行并避免这种效果(我可能做错了)吗?

谢谢!

在将图像提供给UIImageView:的图像属性之前,您可以为UIImage类创建一个类别,用于在后台线程中预加载图像

h:

#import <Foundation/Foundation.h>
@interface UIImage (preloadedImage)
- (UIImage *) preloadedImage;
@end

m:

#import "UIImage+preloadedImage.h"
@implementation UIImage (preloadedImage)
- (UIImage *) preloadedImage {
    CGImageRef image = self.CGImage;
    // make a bitmap context of a suitable size to draw to, forcing decode
    size_t width = CGImageGetWidth(image);
    size_t height = CGImageGetHeight(image);
    CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef imageContext =  CGBitmapContextCreate(NULL, width, height, 8, width * 4, colourSpace,
                                                       kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
    CGColorSpaceRelease(colourSpace);
    // draw the image to the context, release it
    CGContextDrawImage(imageContext, CGRectMake(0, 0, width, height), image);
    // now get an image ref from the context
    CGImageRef outputImage = CGBitmapContextCreateImage(imageContext);
    UIImage *cachedImage = [UIImage imageWithCGImage:outputImage];
    // clean up
    CGImageRelease(outputImage);
    CGContextRelease(imageContext);
    return cachedImage;
}
@end

然后在后台线程上调用preloadedImage,并在主线程上设置结果。

最新更新