使用CALayer的renderInContext:方法与geometryFlipped [英] Using CALayer's renderInContext: method with geometryFlipped

查看:707
本文介绍了使用CALayer的renderInContext:方法与geometryFlipped的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

为了参考,下面的代码实际上保存了生成的 NSBitmapImageRep

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


推荐答案

您需要翻转目标上下文 BEFORE

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

这篇关于使用CALayer的renderInContext:方法与geometryFlipped的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆