我有一些代码可以连续生成动画的UIImage帧。目前我正在使用一个可变数组来保存这些图像对象,这些图像对象可以使用UIImageView动画方法进行动画处理。如下所示:
NSMutableArray *myFrames...;
while ( number of frames required ) {
create UIImage frame_xx;
[myFrames addObject:frame_xx];
}
myUImageView.animationImages = myFrames;
myUImageView.animationDuration = time_length_for_animation;
[myUImageView startAnimating];
上面的代码工作正常,但我的问题是,当我的动画变得超过几百帧时,我开始得到内存警告,最终程序崩溃。
我理想的做法是立即显示每个帧,而不是为动画生成一堆帧。动画可能会慢一点,但我不会局限于内存。一旦显示frame_xx,我就不再关心那个帧了,并希望显示下一帧。
我尝试使用以下内容但它们不起作用:
[myUImageView setImage:frame_xx] // This only displays the last frame generated in the loop
我也试过创建一个新线程:
[NSThread detachNewThreadSelector: @selector(displayImage) toTarget:myUImageView withObject:frame_xx]; // again this only shows the last frame generated in the loop
所以我正在寻求帮助..你如何在UIImageView中立即显示一个图像框,有点像[myUImageView setImage:frame_xxx]之后的“flush”一样
对此的任何帮助将不胜感激..
KAS
答案 0 :(得分:2)
你试过NSTimer
吗?有更准确的方法来管理时序,但如果您的帧速率相当低,这应该适用于基本需求。在这个例子中,我使用的是10fps。 (我还没有编译这段代码。)
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(nextFrame:) userInfo:nil repeats:YES];
...
- (void)nextFrame:(NSTimer*)timer {
UIImage *image = ... generate image ...
[self.imageView setImage:image];
}
当前设计中的根本问题是,如果要绘制图像,则必须允许runloop完成。你不能也不应该在事件循环中引起绘图。
答案 1 :(得分:0)
您是否尝试过不使用UIImageView并在drawRect:方法中绘制图像?
类似的东西:
[image drawInRect:rect]; // where 'rect' is the frame for the image
此外,永远不要在单独的线程中进行任何UI绘图。这样做会导致随机和持续的崩溃。 NSThread#detachNewThreadSelector不是在iOS上执行多线程任务的首选方法。看看NSOperation和NSOperationQueue。然后当你需要向UI用户绘制NSObject的实例方法performSelectorOnMainThread:。