0
+(UIImage*) createCGImageFromFile:(NSString*)inName
{
    if(!inName || [inName length]==0)
        return  NULL;

    // use the data provider to get a CGImage; release the data provider
    CGImageRef image= NULL;
    CGFloat scale = 1.0f;
    CGDataProviderRef dataProvider = NULL;

    NSString *fileName = nil;
    NSString *path = nil;
    if([Utilities isRetinaDevice])
    {
        NSString *extenstion = [inName pathExtension];
        NSString *stringWithoutPath = [inName stringByDeletingPathExtension];
        fileName = [NSString stringWithFormat:@"/Images/%@@2x.%@",stringWithoutPath,extenstion];
        path = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:fileName];
        dataProvider = CGDataProviderCreateWithFilename([path UTF8String]);
        if(dataProvider)
        {
            image = CGImageCreateWithPNGDataProvider(dataProvider, NULL, NO,kCGRenderingIntentDefault);
            CGDataProviderRelease(dataProvider);
            if(image)
            {
                scale = 2.0f;
            }
        }
    }

    if(image == NULL) //Try normal image
    {
        fileName =  [NSString stringWithFormat:@"/Images/%@",inName];
        path = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:fileName];
        dataProvider = CGDataProviderCreateWithFilename([path UTF8String]);
        if(dataProvider)
        {
            image = CGImageCreateWithPNGDataProvider(dataProvider, NULL, NO,kCGRenderingIntentDefault);
            CGDataProviderRelease(dataProvider);
        }
    }

    // make a bitmap context of a suitable size to draw to, forcing decode
    size_t width = CGImageGetWidth(image);
    size_t height = CGImageGetHeight(image);
    unsigned char *imageBuffer = (unsigned char *)malloc(width*height*4);

    CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();

    CGContextRef imageContext =
    CGBitmapContextCreate(imageBuffer, width, height, 8, width*4, colourSpace,
                          kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);

    CGColorSpaceRelease(colourSpace);

    // draw the image to the context, release it
    CGContextDrawImage(imageContext, CGRectMake(0, 0, width, height), image);
    CGImageRelease(image);

    // now get an image ref from the context
    CGImageRef cgImageRef = CGBitmapContextCreateImage(imageContext);

    CGContextRelease(imageContext);
    free(imageBuffer);

    UIImage *outImage = nil;
    if(cgImageRef)
    {
        outImage = [[UIImage alloc] initWithCGImage:cgImageRef scale:scale orientation:UIImageOrientationUp];
        CGImageRelease(cgImageRef);
    }

    return outImage;//Need to release by the receiver
}

早些时候,该功能没有加载视网膜图像,因为我没有将@2x 附加到图像路径,我认为苹果本身会小心的。现在我修改了代码以加载@2x 图像并使用比例因子创建 UIImage,我在上面的代码中遗漏了什么吗?好吗?

PS 目前我在使用此代码时没有遇到任何问题,但我不是 100% 确定

4

1 回答 1

0

我会使用 UIImage 来加载它(它会更正路径)这将大大简化您的代码

然后从中获取 CGImage (UIImage 基本上只是 CG 的薄包装,因此没有真正的开销)

然后继续执行您的代码-对我来说还可以

于 2012-11-22T07:48:29.207 回答