iOS长图生成的pdf性能优化记录

2024-01-22 10:44

本文主要是介绍iOS长图生成的pdf性能优化记录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

背景

  某日产品拿来了一个由30多页高清长图生成的pdf,在应用中运行出现了崩溃。

排查

  经过调试发现加载长图生成的pdf时,运行内存会出现缓慢增长,直至崩溃。经过代码定位发现时pdf转成image对象的过程中由于是长图生成的pdf,这一页的pdf的size相当于正常pdfsize的30多页,转换的过程中context的fill的size也是正常pdf的30多倍。经过调研,尝试,发现对于同一页的pdf,可以通过调整context的fill的size来只把pdf中的部分内容转换成image对象,内存正常也不大。

方案

  原来的方案是每页pdf生成一个image对象,通过一个collectonViewCell来显示。调整后的方案为:根据屏幕大小来决定一个pdf页面生成多少个image对象,有多少个image对象,一个section里就有多少个cell。方案如下:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {if pdfSize.height/pdfSize.width >= 3.0 { //长图生成的pdf 备注:pdfSize 即一页pdf的大小let visible_width = pdfSize.widthlet visible_height = visible_width * Board_height/Board_widthlet visibleSize = CGSize(width: visible_width, height: visible_height)let count:Int = Int(ceil(pdfSize.height/visible_height))// 计算需要分割的次数let index:Intlet itemSize:CGSizeif indexPath.item < count {index = indexPath.item} else {index = count - 1}if CGFloat(index) * visibleSize.height + visibleSize.height < pdfSize.height {itemSize = visibleSize} else {let tailHeight = pdfSize.height - CGFloat(index) * visibleSize.heightitemSize = CGSize(width: visibleSize.width, height: tailHeight)}return itemSize}return pdfSize}

在讲pdf转成image对象的过程中,方案调整核心代码如下:

//index就是pdf中的从上往下被分割后的image的索引值private func subImageFromLongPDF(ori_page:PDFPage, pdfSize:CGSize, index:Int) -> UIImage {guard let page = ori_page.pageRef else {return UIImage()}var dic = [PDFAnnotation:CGRect]()let originalPageRect = ori_page.originalPageRectlet elaborate: CGFloat = 1.0let scale_W = pdfSize.width / originalPageRect.size.width * elaboratelet scale_H = pdfSize.height / originalPageRect.size.height * elaboratelet width = originalPageRect.size.width * scale_Wlet height = width * Board_height/Board_width // Board_height屏幕高度,Board_width屏幕宽度let visibleSize = CGSize(width: width, height: height)let rotation = ori_page.rotationori_page.rotation = 0let scaledOrigin = CGPoint(x: originalPageRect.origin.x * scale_W, y: originalPageRect.origin.y * scale_H)let scaledPageSize = CGSize(width: originalPageRect.size.width * scale_W, height: originalPageRect.size.height * scale_H)let scaledPageRect:CGRectvar tailHeight = 0.0if CGFloat(index) * visibleSize.height + height < scaledPageSize.height {scaledPageRect = CGRect(origin: CGPoint(x: 0, y: CGFloat(index) * visibleSize.height), size: visibleSize)} else {tailHeight = scaledPageSize.height - CGFloat(index) * visibleSize.heightscaledPageRect = CGRect(origin: CGPoint(x: 0, y: CGFloat(index) * visibleSize.height), size: CGSize(width: visibleSize.width, height: tailHeight))}var img:UIImage?autoreleasepool {let renderer = UIGraphicsImageRenderer(size: scaledPageRect.size)var tmpImg:UIImage? = renderer.image {ctx inUIColor.white.set()//这个核心代码,scaledPageRect就是计算好的rect,ctx.fill(scaledPageRect)let rotationAngle: CGFloatswitch page.rotationAngle {//保持和安卓一致,强制为0了case 90:rotationAngle = 270//平移 以用户空间为单位,指定上下文的坐标空间 x 轴的位移量。ctx.cgContext.translateBy(x: -scaledPageRect.origin.x, y: 0)case 180:rotationAngle = 180//平移ctx.cgContext.translateBy(x: scaledPageRect.width,y: 0)case 270:rotationAngle = 90//平移ctx.cgContext.translateBy(x: scaledPageRect.origin.x, y: scaledPageRect.size.height - scaledPageRect.origin.y)default:rotationAngle = 0//平移 以用户空间为单位,指定上下文的坐标空间 x 轴的位移量。//指定上下文的坐标空间 y 轴的位移量(以用户空间为单位)。if rotation == 180 {if tailHeight > 0 {//尾部不足一屏的特殊处理逻辑ctx.cgContext.translateBy(x: 0 - scaledOrigin.x, y: 0 + scaledOrigin.y + CGFloat(index+1) * visibleSize.height - (visibleSize.height - tailHeight))//翻转180度正常} else {ctx.cgContext.translateBy(x: 0 - scaledOrigin.x, y: 0 + scaledOrigin.y + CGFloat(index+1) * visibleSize.height)//翻转180度正常}} else {ctx.cgContext.translateBy(x: 0 - scaledOrigin.x, y: scaledPageSize.height + scaledOrigin.y - scaledPageRect.origin.y)}}//Rotate是以原点为圆心旋转,Quartz创建的图形上下文旋转圆心为左下角,角度值正数为逆时针旋转,负数为顺时针旋转//UIKit创建的图像上下文旋转圆心为左上角,角度值正数为顺时针旋转,负数为逆时针旋转。// Flip the context vertically because the Core Graphics coordinate system starts from the bottom.ctx.cgContext.scaleBy(x:1.0, y: -1.0)//垂直翻转上下文,因为核心图形坐标系从底部开始//旋转 正值逆时针旋转,负值顺时针旋转ctx.cgContext.rotate(by: rotationAngle.degreesToRadians)ctx.cgContext.scaleBy(x: scale_W, y: scale_H)//缩放// Draw the PDF page.// 此处仍然是正常的绘制pdf,因为前面设置了context的fillSize,因此pdf绘制的时候只在前面指定的rect才会生效。ctx.cgContext.drawPDFPage(page)for annotation in ori_page.annotations {let origin = annotation.bounds.origindic[annotation] = annotation.boundslet annotation_fill_bounds = CGRect(x: origin.x + originalPageRect.origin.x, y: origin.y + originalPageRect.origin.y, width: annotation.bounds.size.width, height: annotation.bounds.size.height)annotation.bounds = annotation_fill_boundsannotation.draw(with: .cropBox, in: ctx.cgContext)}}if rotation%360 != 0 {let scale:Float =  Float(rotation) / Float(180)tmpImg = tmpImg?.rotate(radians: Float.pi * scale) ?? UIImage.init()}img = tmpImgtmpImg = nil}//将对pdfpage的修改进行还原ori_page.rotation = rotationfor (annotation,bounds) in dic {annotation.bounds = bounds}return img ?? UIImage()}extension PDFPage {var originalPageRect: CGRect {switch rotation {case 90, 270:let originalRect = bounds(for: PDFDisplayBox.cropBox)let rotatedSize = CGSize(width: originalRect.height, height: originalRect.width)return CGRect(origin: originalRect.origin, size: rotatedSize)default:return bounds(for: PDFDisplayBox.cropBox)}}
}extension UIImage {func rotate(radians: Float) -> UIImage? {var newSize = CGRect(origin: CGPoint.zero, size: self.size).applying(CGAffineTransform(rotationAngle: CGFloat(radians))).size// Trim off the extremely small float value to prevent core graphics from rounding it upnewSize.width = floor(newSize.width)newSize.height = floor(newSize.height)UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale)guard let context = UIGraphicsGetCurrentContext() else {return nil}// Move origin to middlecontext.translateBy(x: newSize.width/2, y: newSize.height/2)// Rotate around middlecontext.rotate(by: CGFloat(radians))// Draw the image at its centerself.draw(in: CGRect(x: -self.size.width/2, y: -self.size.height/2, width: self.size.width, height: self.size.height))let newImage = UIGraphicsGetImageFromCurrentImageContext()UIGraphicsEndImageContext()return newImage}
}extension FloatingPoint {var degreesToRadians: Self { return self * .pi / 180 }var radiansToDegrees: Self { return self * 180 / .pi }
}

备注:这段代码结合了自己的项目实际业务,大家作为参考。多看下核心代码和注释

这篇关于iOS长图生成的pdf性能优化记录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/632740

相关文章

Python中4大日志记录库比较的终极PK

《Python中4大日志记录库比较的终极PK》日志记录框架是一种工具,可帮助您标准化应用程序中的日志记录过程,:本文主要介绍Python中4大日志记录库比较的相关资料,文中通过代码介绍的非常详细,... 目录一、logging库1、优点2、缺点二、LogAid库三、Loguru库四、Structlogphp

Java使用Spire.Barcode for Java实现条形码生成与识别

《Java使用Spire.BarcodeforJava实现条形码生成与识别》在现代商业和技术领域,条形码无处不在,本教程将引导您深入了解如何在您的Java项目中利用Spire.Barcodefor... 目录1. Spire.Barcode for Java 简介与环境配置2. 使用 Spire.Barco

C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解

《C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解》:本文主要介绍C++,C#,Rust,Go,Java,Python,JavaScript性能对比全面... 目录编程语言性能对比、核心优势与最佳使用场景性能对比表格C++C#RustGoJavapythonjav

Python结合Free Spire.PDF for Python实现PDF页面旋转

《Python结合FreeSpire.PDFforPython实现PDF页面旋转》在日常办公或文档处理中,我们经常会遇到PDF页面方向错误的问题,本文将分享如何用Python结合FreeSpir... 目录基础实现:单页PDF精准旋转完整代码代码解析进阶操作:覆盖多场景旋转需求1. 旋转指定角度(90/27

使用C#实现将RTF转换为PDF

《使用C#实现将RTF转换为PDF》RTF(RichTextFormat)是一种通用的文档格式,允许用户在不同的文字处理软件中保存和交换格式化文本,下面我们就来看看如何使用C#实现将RTF转换为PDF... 目录Spire.Doc for .NET 简介安装 Spire.Doc代码示例处理异常总结RTF(R

Spring Boot基于 JWT 优化 Spring Security 无状态登录实战指南

《SpringBoot基于JWT优化SpringSecurity无状态登录实战指南》本文介绍如何使用JWT优化SpringSecurity实现无状态登录,提高接口安全性,并通过实际操作步骤... 目录Spring Boot 实战:基于 JWT 优化 Spring Security 无状态登录一、先搞懂:为什

SpringBoot集成iText快速生成PDF教程

《SpringBoot集成iText快速生成PDF教程》本文介绍了如何在SpringBoot项目中集成iText9.4.0生成PDF文档,包括新特性的介绍、环境准备、Service层实现、Contro... 目录SpringBoot集成iText 9.4.0生成PDF一、iText 9新特性与架构变革二、环

使用Python在PDF中绘制多种图形的操作示例

《使用Python在PDF中绘制多种图形的操作示例》在进行PDF自动化处理时,人们往往首先想到的是文本生成、图片嵌入或表格绘制等常规需求,然而在许多实际业务场景中,能够在PDF中灵活绘制图形同样至关重... 目录1. 环境准备2. 创建 PDF 文档与页面3. 在 PDF 中绘制不同类型的图形python

使用Python实现在PDF中添加、导入、复制、移动与删除页面

《使用Python实现在PDF中添加、导入、复制、移动与删除页面》在日常办公和自动化任务中,我们经常需要对PDF文件进行页面级的编辑,使用Python,你可以轻松实现这些操作,而无需依赖AdobeAc... 目录1. 向 PDF 添加空白页2. 从另一个 PDF 导入页面3. 删除 PDF 中的页面4. 在

CPython与PyPy解释器架构的性能测试结果对比

《CPython与PyPy解释器架构的性能测试结果对比》Python解释器的选择对应用程序性能有着决定性影响,CPython以其稳定性和丰富的生态系统著称;而PyPy作为基于JIT(即时编译)技术的替... 目录引言python解释器架构概述CPython架构解析PyPy架构解析架构对比可视化性能基准测试测