5

我只想预渲染不同的图像以便快速访问。我在这里使用大中央调度来执行不同的块。

启动队列后,我想在完成后设置第一张图像。使用下面的当前代码,不幸的是,只有在渲染完所有图像后才会显示第一张图像。

那么如何修改代码呢?每张图片完成后是否有可能获得委托?

这是代码:

// Async prerendering
    for (int i = 0; i < count; i++) {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

            dispatch_async(dispatch_get_main_queue(), ^{

                UIImage* finalImage = [self prerenderImageForIndex:i];
                [self.imageArray addObject:finalImage];   

                // TODO: i want to display the first image. 
                // rendering goes on in the background 

               if (i==0 && [self.imageArray objectAtIndex:0] != nil ) {
                    self.image = [self.imageArray objectAtIndex:0];
                }
            });
        });
    }

更新:

-(UIImage*) prerenderImageForIndex:(int)frame {
 UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.frame.size.width, self.frame.size.height), NO, 0);      

        for (int i=0; i< [configurationArray count]; i++) {     
         //... get the layerName

        UIImage* layerImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:layerName ofType:@"png"]];

              // draw layer with blendmode and alpha 
        [layerImage drawInRect:CGRectMake(x, y, layerImage.size.width, layerImage.size.height) 
                     blendMode:layerblendmode 
                         alpha: layeralpha];

           }   

    // Get current context as an UIImage
    UIImage* finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

return finalImage;

}

我只想知道如何取消/停止或重新启动正在运行的队列?那可能吗?谢谢你的帮助。

4

2 回答 2

2

我不确定为什么你有这样嵌套的 dispatch_async 调用,但也许这就是问题所在。我想像下面这样的东西会完成你想要的。当您真正想要进行 UI 更新时,您只需要获取主队列,其他一切都应该在后台队列中完成。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

    UIImage* finalImage = [self prerenderImageForIndex:i];
    [self.imageArray addObject:finalImage];

    if (i==0 && [self.imageArray objectAtIndex:0] != nil ) {
        dispatch_async(dispatch_get_main_queue(), ^{   
            self.image = [self.imageArray objectAtIndex:0];
        });
    }
});
于 2012-05-04T15:04:43.773 回答
2

您必须使用串行队列,例如执行 FIFO:

dispatch_queue_t queue;
queue = dispatch_queue_create("myImageQueue", NULL);
for(int i = 0; i<count; i++) {
    dispatch_async(queue, ^{
        // do your stuff in the right order
    });
}

对于串行调度队列,请查看:http: //developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

于 2012-05-04T15:28:11.493 回答