如何确保UIImageView的setImage在下一帧之前完成

问题描述

|| 我有一些代码可以连续生成用于动画的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
因此,我正在寻求帮助。.如何在[myUImageView setimage:frame_xxx]之后立即在UIImageView中显示图像框,有点像\“ flush \” 在这方面的任何帮助将不胜感激。 卡斯     

解决方法

        你试过三英镑吗?有更精确的方法来管理时间,但是如果您的帧速率很低,这应该可以满足基本需求。在此示例中,我使用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];
}
当前设计的根本问题是,如果要绘制图像,则必须允许运行循环完成。您不能也不应导致绘图在事件循环的中间发生。     ,        您是否尝试过不使用UIImageView并在drawRect:方法中绘制图像? 就像是:
    [image drawInRect:rect]; // where \'rect\' is the frame for the image
另外,切勿在单独的线程中进行任何UI绘制。这样做会造成随机和持续的崩溃。在iOS上,NSThread#detachNewThreadSelector不是执行多线程任务的首选方法。查看NSOperation和NSOperationQueue。然后,当您需要向UI用户绘制NSObject的实例方法performSelectorOnMainThread:时。