在GCD块中绘制图像时出现口吃



我有以下方法,取一些CAShapeLayers并将它们转换为UIImageUIImage用于UITableView的单元格(非常像照片应用程序,当您从一个库中选择照片时)。这个方法是从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吗?

最后我相信:

[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(); 

在WWDC2012的视频"在iOS上构建并发用户界面"中有一个很好的例子

相关内容

  • 没有找到相关文章

最新更新