CALayer を画像ファイルとして出力する

色々と便利な CALayer ですが、NSView に比べて画像ファイル化しにくい印象を受けます。
CALayer を画像として取得するには、新規作成したコンテキストに CALayer.renderInContext: メソッドでレンダリングし、CGBitmapContextCreateImage() 関数で CGImageRef を得ます。 CGImageRefNSBitmapImageRep を作成するために必要で、最後に NSBitmapImageRep.TIFFRepresentation メソッドで画像データを取得できます。
CALayer.renderInContext: メソッドは、そのサブレイヤも全てレンダリングします。

ソースコードこちら を参照しました。

// 引数 layer を画像データを含む NSBitmapImageRep インスタンスを返す。
- (NSBitmapImageRep *)bitmapImageForLayer:(CALayer *)layer
{
    // 新規コンテキストを作成
    CGContextRef context = NULL;
    CGColorSpaceRef colorSpace;
    int bitmapByteCount;
    int bitmapBytesPerRow;
    
    int pixelsHigh = (int)[layer bounds].size.height;
    int pixelsWide = (int)[layer 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);
    
    // context にレンダリング
    [layer renderInContext:context];  // sublayers もレンダリングされる
    CGImageRef image = CGBitmapContextCreateImage(context);
    
    NSBitmapImageRep *bitmap = [[[NSBitmapImageRep alloc] 
                                 initWithCGImage:image] autorelease];
    CFRelease(image);
    return bitmap;
}

上記メソッドから画像ファイルを保存する手順は以下の通りである。

    NSBitmapImageRep *bitmap = [self bitmapImageForLayer:layer];
    NSData *data = [bitmap TIFFRepresentation];
    // 画像データを保存する
    [data writeToFile:path options:0 error:&error];

参考:objective c - How do I render a view which contains Core Animation layers to a bitmap? - Stack Overflow

Mac OS X Cocoaプログラミング 第三版

Mac OS X Cocoaプログラミング 第三版