Using CALayer's renderInContext: method with geometryFlipped

烂漫一生 提交于 2019-12-18 04:50:35

问题


I have a CALayer (containerLayer) that I'm looking to convert to a NSBitmapImageRep before saving the data out as a flat file. containerLayer has its geometryFlipped property set to YES, and this seems to be causing issues. The PNG file that is ultimately generated renders the content correctly, but doesn't seem to takes the flipped geometry into account. I'm obviously looking for test.png to accurately represent the content shown to the left.

Attached below is a screenshot of the problem and the code I'm working with.

- (NSBitmapImageRep *)exportToImageRep
{
    CGContextRef context = NULL;
    CGColorSpaceRef colorSpace;
    int bitmapByteCount;
    int bitmapBytesPerRow;

    int pixelsHigh = (int)[[self containerLayer] bounds].size.height;
    int pixelsWide = (int)[[self containerLayer] bounds].size.width;

    bitmapBytesPerRow = (pixelsWide * 4);
    bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);

    colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
    context = CGBitmapContextCreate (NULL,
                                     pixelsWide,
                                     pixelsHigh,
                                     8,
                                     bitmapBytesPerRow,
                                     colorSpace,
                                     kCGImageAlphaPremultipliedLast);
    if (context == NULL)
    {
        NSLog(@"Failed to create context.");
        return nil;
    }

    CGColorSpaceRelease(colorSpace);
    [[[self containerLayer] presentationLayer] renderInContext:context];    

    CGImageRef img = CGBitmapContextCreateImage(context);
    NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithCGImage:img];
    CFRelease(img);

    return bitmap;    
}

For reference, here's the code that actually saves out the generated NSBitmapImageRep:

NSData *imageData = [imageRep representationUsingType:NSPNGFileType properties:nil];
[imageData writeToFile:@"test.png" atomically:NO]; 

回答1:


You need to flip the destination context BEFORE you render into it.

Update your code with this, I have just solved the same problem:

CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, pixelsHigh);
CGContextConcatCTM(context, flipVertical);
[[[self containerLayer] presentationLayer] renderInContext:context];


来源:https://stackoverflow.com/questions/7856127/using-calayers-renderincontext-method-with-geometryflipped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!