【问题标题】:How to have CATiledLayer not block the main thread如何让 CATiledLayer 不阻塞主线程
【发布时间】:2010-06-03 14:31:57
【问题描述】:

我正在将CATiledLayer 实现为UIScrollView。在CATiledLayer 中,我有一个函数可以像这样绘制图层:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    CGContextTranslateCTM(ctx, 0.0f, 0.0f);
    CGContextScaleCTM(ctx, 1.0f, -1.0f);

    CGRect box = CGContextGetClipBoundingBox(ctx);

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"urlhere"]];
    UIImage *image = [[UIImage alloc] initWithData:data];

    CGContextDrawImage(ctx, box, [image CGImage]);
    [image release];
    [data release];
}

问题在于,当每个图块正在下载时,它会阻止其他图块的下载。如果这些图块是并行下载的,我会非常喜欢。特别是它会阻止我无法控制的另一个 UI 元素的下载。

基本上,我只需要知道如何在CATiledLayer 绘图消息中异步下载数据。

【问题讨论】:

    标签: iphone objective-c uikit ipad catiledlayer


    【解决方案1】:

    您可以像在任何其他情况下一样使用 NSURLConnection 之类的东西异步下载数据。下载完成后,告诉图层重新绘制,然后调用 -drawLayer:inContext: ,此时您只需抓取下载的图像。换句话说,不要在 -drawLayer 中下载你的数据,也不要使用 -dataWithContentsOfURL,它是同步的,默认是阻塞的。

    【讨论】:

    • 那么在数据下载并绘制到屏幕后,我应该释放 UIImage 吗?如果我平移回来,它还会被画在那里吗?
    • 数据被缓存了,但是你无法控制缓存,所以你的代码应该期望drawLayer:inContext可以被重复调用
    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多