我使用时序配置文件工具来识别95%的时间花在调用CGContextDrawImage函数上。
在我的应用程序中,有很多重复的图像可以从精灵地图中重复切割并绘制到屏幕上。我想知道是否有可能将CGContextDrawImage的输出缓存在NSMutableDictionay中,然后如果再次请求相同的精灵,它可以从缓存中拉出它而不是完成剪切和再次渲染的所有工作。这就是我所拥有的,但我没有成功:
解释
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();
}
答案 0 :(得分:3)
是的,可以缓存渲染图像。以下是如何完成的示例:
+ (UIImage *)getRenderedImage:(UIImage *)image targetSize:(CGSize)targetSize
{
CGRect targetRect = CGRectIntegral(CGRectMake(0, 0, targetSize.width, targetSize.height)); // should be used by your drawing code
CGImageRef imageRef = image.CGImage; // should be used by your drawing code
UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// TODO: draw and clip your image here onto context
// CGContextDrawImage CGContextClipToRect calls
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease(newImageRef);
UIGraphicsEndImageContext();
return newImage;
}
这样,您将获得资源图像的渲染副本。因为在渲染过程中,您拥有上下文,所以您可以自由地执行任何操作。您只需要事先确定输出大小。
生成的图片只是UIImage
的一个实例,您可以将其放入NSMutableDictionary
以供日后使用。