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

相关文章

IDEA自动生成注释模板的配置教程

《IDEA自动生成注释模板的配置教程》本文介绍了如何在IntelliJIDEA中配置类和方法的注释模板,包括自动生成项目名称、包名、日期和时间等内容,以及如何定制参数和返回值的注释格式,需要的朋友可以... 目录项目场景配置方法类注释模板定义类开头的注释步骤类注释效果方法注释模板定义方法开头的注释步骤方法注

在Spring Boot中浅尝内存泄漏的实战记录

《在SpringBoot中浅尝内存泄漏的实战记录》本文给大家分享在SpringBoot中浅尝内存泄漏的实战记录,结合实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录使用静态集合持有对象引用,阻止GC回收关键点:可执行代码:验证:1,运行程序(启动时添加JVM参数限制堆大小):2,访问 htt

Python如何自动生成环境依赖包requirements

《Python如何自动生成环境依赖包requirements》:本文主要介绍Python如何自动生成环境依赖包requirements问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录生成当前 python 环境 安装的所有依赖包1、命令2、常见问题只生成当前 项目 的所有依赖包1、

Android实现打开本地pdf文件的两种方式

《Android实现打开本地pdf文件的两种方式》在现代应用中,PDF格式因其跨平台、稳定性好、展示内容一致等特点,在Android平台上,如何高效地打开本地PDF文件,不仅关系到用户体验,也直接影响... 目录一、项目概述二、相关知识2.1 PDF文件基本概述2.2 android 文件访问与存储权限2.

MySQL 中查询 VARCHAR 类型 JSON 数据的问题记录

《MySQL中查询VARCHAR类型JSON数据的问题记录》在数据库设计中,有时我们会将JSON数据存储在VARCHAR或TEXT类型字段中,本文将详细介绍如何在MySQL中有效查询存储为V... 目录一、问题背景二、mysql jsON 函数2.1 常用 JSON 函数三、查询示例3.1 基本查询3.2

MySQL中动态生成SQL语句去掉所有字段的空格的操作方法

《MySQL中动态生成SQL语句去掉所有字段的空格的操作方法》在数据库管理过程中,我们常常会遇到需要对表中字段进行清洗和整理的情况,本文将详细介绍如何在MySQL中动态生成SQL语句来去掉所有字段的空... 目录在mysql中动态生成SQL语句去掉所有字段的空格准备工作原理分析动态生成SQL语句在MySQL

Python通过模块化开发优化代码的技巧分享

《Python通过模块化开发优化代码的技巧分享》模块化开发就是把代码拆成一个个“零件”,该封装封装,该拆分拆分,下面小编就来和大家简单聊聊python如何用模块化开发进行代码优化吧... 目录什么是模块化开发如何拆分代码改进版:拆分成模块让模块更强大:使用 __init__.py你一定会遇到的问题模www.

详解如何通过Python批量转换图片为PDF

《详解如何通过Python批量转换图片为PDF》:本文主要介绍如何基于Python+Tkinter开发的图片批量转PDF工具,可以支持批量添加图片,拖拽等操作,感兴趣的小伙伴可以参考一下... 目录1. 概述2. 功能亮点2.1 主要功能2.2 界面设计3. 使用指南3.1 运行环境3.2 使用步骤4. 核

Java利用docx4j+Freemarker生成word文档

《Java利用docx4j+Freemarker生成word文档》这篇文章主要为大家详细介绍了Java如何利用docx4j+Freemarker生成word文档,文中的示例代码讲解详细,感兴趣的小伙伴... 目录技术方案maven依赖创建模板文件实现代码技术方案Java 1.8 + docx4j + Fr

SpringBoot首笔交易慢问题排查与优化方案

《SpringBoot首笔交易慢问题排查与优化方案》在我们的微服务项目中,遇到这样的问题:应用启动后,第一笔交易响应耗时高达4、5秒,而后续请求均能在毫秒级完成,这不仅触发监控告警,也极大影响了用户体... 目录问题背景排查步骤1. 日志分析2. 性能工具定位优化方案:提前预热各种资源1. Flowable