问题
I'm developing and iOS app for iPad and I use Grabkit in order to get images from Facebook, Twitter, Flicker and also the Camera Roll. To get the images from the last one, I need to convert a CGImage to an UIImage, but I'm having trouble with that. Is like if I didn't get any image, because when I use the UIImage later, the app crashes with this log:
*** Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan 653]'
I'm using the following code to convert the CGImage:
UIImage* image = [UIImage imageWithCGImage:imgRef];
So this code doesn't crash, but when I use the image created, it does. What is happening? Is the code wrong?
回答1:
You should use alloc init like UIImage* myImage = [[UIImage alloc] initWithCGImage:myCGImage];
or you could try this:
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
int size = height*width*bytesPerPixel;
unsigned char *rawData = malloc(size);
CGContextRef context = CGBitmapContextCreate(rawData,width,height,bitsPerComponent,bytesPerRow,colorSpace,kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0,0,width,height),image);
UIImage *newImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
CGContextRelease(context);
free(rawData);
来源:https://stackoverflow.com/questions/17576054/cgimage-to-uiimage-doesnt-work