首页 文章

CGImage到UIImage不起作用

提问于
浏览
2

我正在为iPad开发和iOS应用程序,我使用Grabkit来获取来自Facebook,Twitter,Flicker和相机胶卷的图像 . 要从最后一个获取图像,我需要将CGImage转换为UIImage,但我遇到了麻烦 . 就像我没有得到任何图像,因为当我稍后使用UIImage时,应用程序崩溃了这个日志:

*** Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan 653]'

我正在使用以下代码转换CGImage:

UIImage* image = [UIImage imageWithCGImage:imgRef];

所以这段代码不会崩溃,但是当我使用创建的图像时,它确实会崩溃 . 怎么了?代码错了吗?

1 回答

  • 10

    你应该像 UIImage* myImage = [[UIImage alloc] initWithCGImage:myCGImage]; 一样使用alloc init

    或者你可以试试这个:

    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);
    

相关问题