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