iphone - 在 GCD block 中绘制图像时卡顿

标签 iphone ios cocoa-touch core-animation grand-central-dispatch

我有以下方法,它采用一些 CAShapeLayers 并将它们转换为 UIImageUIImageUITableView 的单元格中使用(很像当您从您的库中选择一张照片时的照片应用程序)。从 GCD block 中调用此方法:

-(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 上构建并发用户界面”

关于iphone - 在 GCD block 中绘制图像时卡顿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14007738/

相关文章:

ios - 在没有 Realm 的后台线程中创建 Realm 对象,然后将它们传递给主线程

iphone - 子类化 UIWebView 是否会令人不悦?

ios - 使用 Swift 在 UITextFields 之间自动切换

iphone - 使用 NSStream 与 PHP 通信?

iphone - 处理 HTTP post json 请求的 Web 服务器

ios - 如何在ios swift形式的控件之间添加控件

iphone - 是否可以向 UIScrollView 添加固定内容?

ios - UITableView和UISegmentedControl

ios - 如何在 Swift 中创建独特的形状或 UIView

Objective-C 在运行时修改方法的参数