使用带有geometryFlipped的CALayer的renderInContext:方法

ndg*_*ndg 7 cocoa core-graphics calayer nsbitmapimagerep

我有一个CALayer(containerLayer),我想在将NSBitmapImageRep数据保存为平面文件之前将其转换为a .containerLayer将其geometryFlipped属性设置为YES,这似乎导致了问题.最终生成的PNG文件正确呈现内容,但似乎不考虑翻转的几何体.我显然正在寻找test.png来准确地表示左边显示的内容.

下面是问题的截图和我正在使用的代码.

一个直观的例子

- (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;    
}
Run Code Online (Sandbox Code Playgroud)

作为参考,这是实际保存生成的代码NSBitmapImageRep:

NSData *imageData = [imageRep representationUsingType:NSPNGFileType properties:nil];
[imageData writeToFile:@"test.png" atomically:NO]; 
Run Code Online (Sandbox Code Playgroud)

Mar*_*lch 6

您需要渲染之前翻转目标上下文.

用这个更新你的代码,我刚解决了同样的问题:

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