1
我使用時序配置文件工具來確定95%的時間花在調用CGContextDrawImage函數上。iOS - 是否可以緩存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();
}