是否有任何方法可以将托管 NSView 的图层(如屏幕上显示的那样)渲染为 PDF 或位图文件而不实现每个 CALayer 的 –drawInContext:
方法(或类似方法) ,每个图层的委托(delegate)的 -(void)drawLayer:inContext:
方法)?我只希望 NSView 的内容与它们显示的完全一样,并使用最少的额外绘图代码。
我读过很多资料,说要渲染为 PDF,您必须实现 -drawInContext:
,如果您正在处理自定义图层子类,这是有意义的(否则,如何否则它会知道要绘制什么),但我想渲染当您将图层添加到 View 时“正常工作”的图层,例如 CATextLayer 或 CAShapeLayer。当 CATextLayer 显然完全有能力在屏幕上绘制自己时,必须重写代码来告诉它如何绘制自己,这似乎是完全多余的。
我错过了一些明显的事情吗?
最佳答案
我已使用以下代码成功将 View 的图层层次结构写入 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];
}
关于cocoa - 如何将托管 NSView 的图层渲染到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32619372/