iOS-是否可以缓存CGContextDrawImage?
我使用计时配置文件工具来确定95%的时间都花在调用函数CGContextDrawImage上 在我的应用程序中,有许多重复的图像被从精灵地图上截取并绘制到屏幕上。我想知道是否有可能将CGContextDrawImage的输出缓存在NSMutableDictionary中,然后如果再次请求相同的精灵,则可以将其从缓存中拉出,而不是再次执行所有剪辑和渲染工作。这就是我所得到的,但我没有成功: 定义iOS-是否可以缓存CGContextDrawImage?,ios,caching,core-animation,cgcontextdrawimage,Ios,Caching,Core Animation,Cgcontextdrawimage,我使用计时配置文件工具来确定95%的时间都花在调用函数CGContextDrawImage上 在我的应用程序中,有许多重复的图像被从精灵地图上截取并绘制到屏幕上。我想知道是否有可能将CGContextDrawImage的输出缓存在NSMutableDictionary中,然后如果再次请求相同的精灵,则可以将其从缓存中拉出,而不是再次执行所有剪辑和渲染工作。这就是我所得到的,但我没有成功: 定义 if(cache == NULL) cache = [[NSMutableDictionary all
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();
}
是的,可以缓存渲染图像。下面是如何完成的示例:
+ (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
中供以后使用