【问题标题】:Using CALayer's renderInContext: method with geometryFlipped使用 CALayer 的 renderInContext: 方法和 geometryFlipped
【发布时间】:2011-10-21 22:54:24
【问题描述】:

我有一个 CALayer (containerLayer),我希望在将数据保存为平面文件之前将其转换为 NSBitmapImageRepcontainerLayergeometryFlipped 属性设置为 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;    
}

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

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

【问题讨论】:

    标签: cocoa core-graphics calayer nsbitmapimagerep


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      相关资源
      最近更新 更多