如何渲染一个复杂的UIView到高分辨率的PDF上下文?

关于如何将UIView渲染到PDF上下文中,有几个问题,但他们都使用view.layer.renderInContext(pdfContext),这导致72 DPI图像(打印时看起来很糟糕)。 我正在寻找的是一种技术,以某种方式让UIView呈现像300 DPI的东西。

最后,我从之前的几个post中得到了一些提示,并提出了一个解决scheme。 因为我花了很长时间才开始工作,所以我发布了这个内容,我真的希望能够帮助别人节省时间和精力。

该解决scheme使用两种基本技术:

  1. 将UIView渲染到缩放的位图上下文中以生成大图像
  2. 将图像绘制成缩小的PDF上下文,以使绘制的图像具有高分辨率

build立你的观点:

let v = UIView() ... // then add subviews, constraints, etc 

创buildPDF上下文:

 UIGraphicsBeginPDFContextToData(data, docRect, stats.headerDict) // zero == (612 by 792 points) defer { UIGraphicsEndPDFContext() } UIGraphicsBeginPDFPage(); guard let pdfContext = UIGraphicsGetCurrentContext() else { return nil } // I tried 300.0/72.0 but was not happy with the results let rescale: CGFloat = 4 // 288 DPI rendering of VIew // You need to change the scale factor on all subviews, not just the top view! // This is a vital step, and there may be other types of views that need to be excluded 

然后用扩大的比例创build一个大的位图:

 func scaler(v: UIView) { if !v.isKindOfClass(UIStackView.self) { v.contentScaleFactor = 8 } for sv in v.subviews { scaler(sv) } } scaler(v) // Create a large Image by rendering the scaled view let bigSize = CGSize(width: v.frame.size.width*rescale, height: v.frame.size.height*rescale) UIGraphicsBeginImageContextWithOptions(bigSize, true, 1) let context = UIGraphicsGetCurrentContext()! CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor) CGContextFillRect(context, CGRect(origin: CGPoint(x: 0, y: 0), size: bigSize)) // Must increase the transform scale CGContextScaleCTM(context, rescale, rescale) v.layer.renderInContext(context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() 

现在我们有一个大的图像,每个点代表一个像素。 为了以高分辨率将其绘制到PDF中,我们需要在以大尺寸绘制图像时缩小PDF:

 CGContextSaveGState(pdfContext) CGContextTranslateCTM(pdfContext, v.frame.origin.x, v.frame.origin.y) // where the view should be shown CGContextScaleCTM(pdfContext, 1/rescale, 1/rescale) let frame = CGRect(origin: CGPoint(x: 0, y: 0), size: bigSize) image.drawInRect(frame) CGContextRestoreGState(pdfContext) ... // Continue with adding other items 

你可以看到,奶油色的位图中包含的左边的“S”看起来相当不错,而“S”却是一个属性string:

在这里输入图像说明

当通过PDF的简单渲染而没有进行全部缩放来查看相同的PDF时,您将看到:

在这里输入图像说明