2011-10-21 21 views
7

我有一個CALayer(containerLayer),我希望在將數據保存爲平面文件之前將其轉換爲NSBitmapImageRepcontainerLayer將其geometryFlipped屬性設置爲YES,並且這似乎是導致問題的原因。最終生成的PNG文件會正確呈現內容,但似乎沒有考慮翻轉的幾何圖形。我顯然在尋找test.png來準確地表示左側顯示的內容。使用CALayer的renderInContext:方法geometryFlipped

下面附加了問題和我正在使用的代碼的屏幕截圖。

A visual example

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

回答

6

你需要翻轉目的地上下文你渲染了進去。

更新與此代碼,我剛剛解決了同樣的問題:

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