UIImage的CGImage返回NULL

Oti*_*ium 7 objective-c uiimage cgimage ios

我创建了一个将图像分割成多个图像的函数,但是当我拿到UIImage的CGImage时,CGImage返回NULL

NSArray* splitImage(UIImage* image,NSUInteger pieces) {

NSLog(@"width: %f, %zu",image.size.width,CGImageGetWidth(image.CGImage));
NSLog(@"%@",image.CGImage);
returns NULL
NSMutableArray* tempArray = [[NSMutableArray alloc]initWithCapacity:pieces];

CGFloat piecesSize = image.size.height/pieces;

for (NSUInteger i = 0; i < pieces; i++) {

    // take in account retina displays
    CGRect subFrame = CGRectMake(0,i * piecesSize * image.scale ,image.size.width * image.scale,piecesSize * image.scale);

    CGImageRef newImage = CGImageCreateWithImageInRect(image.CGImage,subFrame);

    UIImage* finalImage =[UIImage imageWithCGImage:newImage];

    CGImageRelease(newImage);

    [tempArray addObject:finalImage];

}

NSArray* finalArray = [NSArray arrayWithArray:tempArray];

[tempArray release];

return finalArray;



}
Run Code Online (Sandbox Code Playgroud)

And*_*kyi 7

我创建UIImageCGImage

CIImage *ciImage = image.CIImage;
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef ref = [context createCGImage:ciImage fromRect:ciImage.extent];
UIImage *newImage = [UIImage imageWithCGImage:ref];
Run Code Online (Sandbox Code Playgroud)

现在newImage.CGImage不是nil


Oti*_*ium 6

如果UIImage是从另一个图像(例如IOSurface或CIImage)创建的,则CGImage属性将返回nil。为了解决这种特殊情况,我可以使用c函数从IOSurface创建CGImage,然后将其转换为UIImage。

UICreateCGImageFromIOSurface(IOSurfaceRef surface);
Run Code Online (Sandbox Code Playgroud)