1

我使用以下方法需要一些CAShapeLayers并将它们转换为UIImageUIImage在单元格中用于UITableView(非常类似于从您的某个库中选择照片时的照片应用程序)。这种方法是从GCD块中调用:在GCD中绘制图像时出现口吃障碍

-(UIImage*) imageAtIndex:(NSUInteger)index 
{ 
    Graphic *graphic = [[Graphic graphicWithType:index]retain]; 

    CALayer *layer = [[CALayer alloc] init]; 
    layer.bounds = CGRectMake(0,0, graphic.size.width, graphic.size.height); 
    layer.shouldRasterize = YES; 
    layer.anchorPoint = CGPointZero; 
    layer.position = CGPointMake(0, 0); 

    for (int i = 0; i < [graphic.shapeLayers count]; i++) 
    { 
     [layer addSublayer:[graphic.shapeLayers objectAtIndex:i]]; 
    } 

    CGFloat largestDimension = MAX(graphic.size.width, graphic.size.height); 
    CGFloat maxDimension = self.thumbnailDimension; 
    CGFloat multiplicationFactor = maxDimension/largestDimension; 
    CGSize graphicThumbnailSize = CGSizeMake(multiplicationFactor * graphic.size.width, multiplicationFactor * graphic.size.height); 

    layer.sublayerTransform = CATransform3DScale(layer.sublayerTransform, graphicThumbnailSize.width/graphic.size.width, graphicThumbnailSize.height/graphic.size.height, 1); 
    layer.bounds = CGRectMake(0,0, graphicThumbnailSize.width, graphicThumbnailSize.height); 

    UIGraphicsBeginImageContextWithOptions(layer.bounds.size, NO, 0); 
    [layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage *image = [UIGraphicsGetImageFromCurrentImageContext() retain]; 
    UIGraphicsEndImageContext(); 

    [layer release]; 
    [graphic release]; 

    return [image autorelease]; 
} 

无论出于何种原因,当我滚动UITableView和,它是口吃有点加载图像。我知道GCD代码很好,因为它以前的工作,所以它似乎在此代码中的东西造成的口吃。有谁知道这可能是什么? CAAnimation不是线程安全的?或者是否有人知道更好的方法来采取一堆CAShapeLayers并将它们转换为UIImage

+0

您是否使用仪器检查帧率?另外当你说,你正在使用GCD,你是否在异步队列上运行整个事情。我敢肯定你是。当你说口吃的时候,你能详细说明你看到的是什么,它是为了进入视野中的新细胞吗... – Srikanth

+0

@Srikanth - 是的,图像加载到表格中时的帧频是35-40。但是,在我缓存了它们之后,它是60.是的,它位于异步队列中。通过口吃我的意思是,当我滚动tableview尽可能快和滚动不光滑,它会停止和去(大概是做加载)。 –

回答

1

最后,我相信:

[layer renderInContext:UIGraphicsGetCurrentContext()]; 

不能在一个单独的线程来完成,所以我不得不做以下几点:

UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0); 
CGContextRef context = UIGraphicsGetCurrentContext(); 
//draw the mutable paths of the CAShapeLayers to the context 
UIImage *image = [UIGraphicsGetImageFromCurrentImageContext() retain]; 
UIGraphicsEndImageContext(); 

还有就是一个很好的例子(其中I学会了这样做)在WWDC2012视频“在iOS上构建并发用户界面”