我有一个 iPad 应用程序,我正在尝试从 UIView 生成 PDF,它几乎完美地工作。
代码很简单如下:
UIGraphicsBeginPDFContextToFile( filename, bounds, nil );
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[view.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
除了一个奇怪的异常(exception),这真的很有效。如果 View 在呈现为 PDF 之前已经显示在屏幕上,则 View 上的 UILabels 将作为美妙的矢量呈现为 PDF。如果 View 还没有出现在屏幕上(IE Controller 是 initWithNib 等,但还没有被插入导航 Controller 或其他任何东西),那么文本将以“ipad”分辨率呈现为位图。
这就像在我随后将 View 渲染到 pdf 上下文时将渲染到屏幕的行为设置为将 View 渲染为矢量。
是否有一些我可以调用的方法或我可以在 View 、层或其他地方设置的属性来模拟这种行为而不必在屏幕上显示 View ?
和UIViewPrintFormatter有关系吗?
最佳答案
我发现使标签呈现矢量化的唯一方法是通过以下方法使用 UILabel 的子类:
/** Overriding this CALayer delegate method is the magic that allows us to draw a vector version of the label into the layer instead of the default unscalable ugly bitmap */
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
BOOL isPDF = !CGRectIsEmpty(UIGraphicsGetPDFContextBounds());
if (!layer.shouldRasterize && isPDF)
[self drawRect:self.bounds]; // draw unrasterized
else
[super drawLayer:layer inContext:ctx];
}
swift 5.x:
override func draw(_ layer: CALayer, in ctx: CGContext) {
let isPDF = !UIGraphicsGetPDFContextBounds().isEmpty
if !self.layer.shouldRasterize && isPDF {
self.draw(self.bounds)
} else {
super.draw(layer, in: ctx)
}
}
这对我有用:标签在生成的 PDF View 中是未栅格化的和可选择的,并且在呈现到屏幕时表现正常。
关于ios - 在 iPad 上将 UIView 作为矢量渲染到 PDF - 有时渲染为位图,有时渲染为矢量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6423059/