如何呈现托管NSView的文件层

时间:2015-09-16 21:50:35

标签: cocoa core-animation calayer nsview catextlayer

有没有办法在不使用实现每个CALayer的display()方法(或者类似地,每个图层的委托的{{}>的情况下,将一个托管NSView的图层(如屏幕上显示的那样)呈现给PDF或位图文件 {1}}方法)?我只是希望NSView的内容与最小的额外绘图代码完全一样。

我已经读过许多来源,说要渲染到PDF,你必须实现landing,如果你正在处理一个自定义的子类,这是有意义的(否则,它怎么会知道什么绘制),但我希望在将它们添加到视图时(例如CATextLayer或CAShapeLayer)渲染“正常工作”的图层。似乎完全没有必要重写CATextLayer的代码,告诉它如何绘制自己,当它显然完全能够在屏幕上执行此操作时。

我错过了一些明显的东西吗?

1 个答案:

答案 0 :(得分:4)

我已使用以下代码成功地将视图的图层层次结构写入PDF:

- (void)renderToPath:(NSString *)filePath
{
    NSImage *image = [[NSImage alloc] initWithSize:self.bounds.size];
    [image lockFocus];
    [self.layer renderInContext:[NSGraphicsContext currentContext].CGContext];
    [image unlockFocus];

    NSImageView *tempImageView = [[NSImageView alloc] initWithFrame:self.bounds];
    tempImageView.image = image;
    NSData *pdf = [tempImageView dataWithPDFInsideRect:self.bounds];
    [pdf writeToFile:filePath atomically:YES];
}

Here's a sample project