1

我使用时序分析工具确定 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();
}
4

1 回答 1

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供以后使用的一个实例。

于 2012-03-31T11:22:51.707 回答