2012-03-31 72 views
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(); 
} 

回答

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供以後使用。

相關問題