+(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,我在上面的代码中遗漏了什么?好吗?
P.S。目前我没有遇到任何使用此代码的问题,但我不是百分百肯定
答案 0 :(得分:0)
我会用UIImage加载它(它会纠正路径) 这将极大只是你的代码
然后从中获取CGImage(UIImage基本上只是CG的一个薄包装,因此没有真正的开销)
然后继续你的代码 - 它对我来说没问题