在 iPad 上将 UIView 作为矢量渲染为 PDF - 有时渲染为位图,有时渲染为矢量 [英] Rendering a UIView into a PDF as vectors on an iPad - Sometimes renders as bitmap, sometimes as vectors

查看:22
本文介绍了在 iPad 上将 UIView 作为矢量渲染为 PDF - 有时渲染为位图,有时渲染为矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 iPad 应用程序,我正在尝试从 UIView 生成 PDF,它几乎完美运行.

I have an iPad app and I'm trying to generate a PDF from a UIView and it's almost working perfectly.

代码非常简单如下:

UIGraphicsBeginPDFContextToFile( filename, bounds, nil );
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[view.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();

这非常有效,但有一个奇怪的例外.如果视图在呈现为 PDF 之前已经在屏幕上,则视图上的 UILabels 将作为美妙的矢量呈现为 PDF.如果视图还没有出现在屏幕上(即控制器是 initWithNib 等,但没有被推入导航控制器或任何东西),那么文本将呈现为ipad"分辨率的位图.

This works really well with one weird exception. If the view has been on screen before being rendered to PDF then the UILabels on the view are rendered to the PDF as wonderful vectors. If the view has not yet been on the screen (IE the controller was initWithNib etc but hasn't been pushed into a navigation controller or anything) then the text is rendered as a bitmap at 'ipad' resolution.

这就像渲染到屏幕的行为将视图设置为在我随后将其渲染到 pdf 上下文时渲染为向量.

It's like the act of getting rendered to the screen sets up the view to be rendered as vectors when I subsequently render it to a pdf context.

是否有一些我可以调用的方法或我可以在视图或图层或其他地方设置的属性来模仿这种行为而不必在屏幕上显示视图?

Is there some method I can call or property I can set on the view or the layer or elsewhere to mimic this behaviour without having to show the view on screen?

是否与 UIViewPrintFormatter 有关?

Is it something to do with UIViewPrintFormatter?

推荐答案

我发现使标签呈现矢量化的唯一方法是使用 UILabel 的子类和以下方法:

The only way I found to make it so labels are rendered vectorized is to use a subclass of UILabel with the following method:

/** 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 视图中是未光栅化和可选择的,并且在呈现到屏幕时表现正常.

That does the trick for me: labels are unrasterized and selectable in the resulting PDF view, and behave normally when rendered to the screen.

这篇关于在 iPad 上将 UIView 作为矢量渲染为 PDF - 有时渲染为位图,有时渲染为矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆