2011-10-21 13 views
7

Tôi có một CALayer (containerLayer) mà tôi đang tìm cách chuyển đổi thành NSBitmapImageRep trước khi lưu dữ liệu ra dưới dạng tệp phẳng. containerLayer có thuộc tính geometryFlipped được đặt thành YES và điều này dường như đang gây ra sự cố. Tệp PNG được tạo cuối cùng sẽ hiển thị nội dung chính xác, nhưng dường như không đưa hình học được lật vào tài khoản. Tôi rõ ràng đang tìm test.png để thể hiện chính xác nội dung được hiển thị ở bên trái.Sử dụng renderInContext của CALayer: phương thức với geometryFlipped

Đính kèm bên dưới là ảnh chụp màn hình sự cố và mã tôi đang làm việc.

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

Để tham khảo, đây là đoạn code mà thực sự tiết kiệm ra tạo NSBitmapImageRep:

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

Trả lời

6

Bạn cần phải lật bối cảnh nơi TRƯỚC bạn render vào nó.

Cập nhật mã của bạn với điều này, tôi đã chỉ giải quyết cùng một vấn đề:

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