我使用时序分析工具确定 95% 的时间都花在调用函数 CGContextDrawImage 上。
在我的应用程序中,有很多重复的图像被重复地从精灵地图中截取并绘制到屏幕上。我想知道是否可以在 NSMutableDictionay 中缓存 CGContextDrawImage 的输出,然后如果再次请求相同的精灵,它可以从缓存中拉出它,而不是做所有的剪辑和渲染工作。这就是我所拥有的,但我还没有成功:
定义
if(cache == NULL) cache = [[NSMutableDictionary alloc]init];
//Identifier based on the name of the sprite and location within the sprite.
NSString* identifier = [NSString stringWithFormat:@"%@-%d",filename,frame];
添加到缓存
CGRect clippedRect = CGRectMake(0, 0, clipRect.size.width, clipRect.size.height);
CGContextClipToRect( context, clippedRect);
//create a rect equivalent to the full size of the image
//offset the rect by the X and Y we want to start the crop
//from in order to cut off anything before them
CGRect drawRect = CGRectMake(clipRect.origin.x * -1,
clipRect.origin.y * -1,
atlas.size.width,
atlas.size.height);
//draw the image to our clipped context using our offset rect
CGContextDrawImage(context, drawRect, atlas.CGImage);
[cache setValue:UIGraphicsGetImageFromCurrentImageContext() forKey:identifier];
UIGraphicsEndImageContext();
渲染缓存的精灵 可能有更好的方法来渲染 CGImage,这是我的最终缓存目标,但目前我只是想成功地渲染缓存的图像,但这并没有成功。
UIImage* cachedImage = [cache objectForKey:identifier];
if(cachedImage){
NSLog(@"Cached %@",identifier);
CGRect imageRect = CGRectMake(0,
0,
cachedImage.size.width,
cachedImage.size.height);
if (NULL != UIGraphicsBeginImageContextWithOptions)
UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, 0);
else
UIGraphicsBeginImageContext(imageRect.size);
//Use draw for now just to see if the image renders out ok
CGContextDrawImage(context, imageRect, cachedImage.CGImage);
UIGraphicsEndImageContext();
}