我找到了解决方法。创建一个串行(一次只有一个操作)调度队列并在其中执行所有绘图,然后缓存结果。
我附上了我正在使用的代码,注意我使用的是 的子类CATiledLayer
,而不是通过委托或其他技术绘制它。
我还创建了一个无限期的切片缓存,根据您的情况,这可能会导致内存问题。您可能需要管理缓存中的切片数量,在添加新切片时删除旧切片。当收到内存不足警告时,还应清除缓存。如果有人添加了这些改进,请随时编辑我的答案以包含它。
- (id)init
{
if (!(self = [super init]))
return nil;
tileCache = [[NSMutableDictionary alloc] init];
return self;
}
- (void)drawInContext:(CGContextRef)layerContext
{
// CATiledLayer has a bug, where it spawns multiple threads for drawing, and then tries to draw the same tile multiple times simultaniously on separate threads
// so we create our own serial background queue, and do dispatch_async on it. This will cache each draw operation, so multiple calls on one tile are efficient
static dispatch_queue_t drawQueue = NULL;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
drawQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
});
dispatch_sync(drawQueue, ^{
// no map ways? draw nothing
if (!self.mapWays)
return;
// load from cache?
CGRect tileRect = CGContextGetClipBoundingBox(layerContext);
NSString *tileCacheKey = [NSString stringWithFormat:@"%f%f%f%f", tileRect.origin.x, tileRect.origin.y, tileRect.size.width, tileRect.size.height];
__block UIImage *tileImage;
dispatch_sync(dispatch_get_main_queue(), ^{
tileImage = [tileCache objectForKey:tileCacheKey];
});
if (tileImage) {
CGContextDrawImage(layerContext, tileRect, tileImage.CGImage);
return;
}
// prepare to draw the tile image
UIGraphicsBeginImageContextWithOptions(tileRect.size, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// filp coords
CGContextTranslateCTM(context, 0, tileRect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
/*** do actual drawing here ***/
// store tile in cache
tileImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_sync(dispatch_get_main_queue(), ^{
[tileCache setObject:tileImage forKey:tileCacheKey];
});
// draw the tile
CGContextDrawImage(layerContext, tileRect, tileImage.CGImage);
});
}