如何渲染一个复杂的UIView到高分辨率的PDF上下文?
关于如何将UIView渲染到PDF上下文中,有几个问题,但他们都使用view.layer.renderInContext(pdfContext),这导致72 DPI图像(打印时看起来很糟糕)。 我正在寻找的是一种技术,以某种方式让UIView呈现像300 DPI的东西。
最后,我从之前的几个post中得到了一些提示,并提出了一个解决scheme。 因为我花了很长时间才开始工作,所以我发布了这个内容,我真的希望能够帮助别人节省时间和精力。
该解决scheme使用两种基本技术:
- 将UIView渲染到缩放的位图上下文中以生成大图像
- 将图像绘制成缩小的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时,您将看到:
- 如何在iOS 6中将背景图像添加到分组样式UITableViewController?
- 只有在分配事件监听器的情况下,CSShover在ios上才有效
- 将Cocoapods添加到多个目标
- 在Swift 3中将可选string转换为double
- iOS中的表单-第1部分
- 我希望两个button具有相同的宽度,并使用自动布局按比例放置在屏幕顶部的所有屏幕尺寸中。
- 在UITableviewcell的ios 11 layoutsubview子视图中找不到UITableViewCellDeleteConfirmationView?
- 在iOS8 / Swift中为UIDatePicker设置文本颜色和字体
- drawRect在突出显示时未调用自定义UIButton子类