PDFKit iOS 11:如何修改墨迹注释(Ink annotation)的线宽?
解决PDFKit墨迹注释(Ink Annotation)线宽修改问题
我之前也踩过这个坑!你用Core Graphics绘图的思路去改UIBezierPath的lineWidth确实不会生效,因为PDFKit里的墨迹注释是基于PDF官方注释规范实现的,它的线宽是作为注释的元数据存储在PDF文件里的,和绘图路径的属性完全是两回事。
要正确修改墨迹注释的线宽,你需要操作PDFAnnotation的border属性,具体步骤如下:
1. 创建墨迹注释时设置线宽
当你创建新的墨迹注释时,不要只关注UIBezierPath的属性,而是要给注释设置PDFBorder对象并指定线宽:
// 1. 创建墨迹路径(这里的lineWidth只是本地绘图预览用,不影响PDF文件中的显示) let inkPath = UIBezierPath() inkPath.move(to: CGPoint(x: 50, y: 50)) inkPath.addLine(to: CGPoint(x: 250, y: 250)) inkPath.lineWidth = 8 // 仅预览生效,实际PDF不生效 // 2. 创建墨迹注释 let inkAnnotation = PDFAnnotation( bounds: inkPath.bounds, forType: .ink, withProperties: nil ) inkAnnotation.add(inkPath) // 3. 设置真正生效的线宽:创建PDFBorder并赋值给注释 let border = PDFBorder() border.lineWidth = 8 // 这个值会写入PDF,在所有阅读器中生效 inkAnnotation.border = border // 4. 将注释添加到PDF页面 if let page = pdfDocument.page(at: 0) { page.addAnnotation(inkAnnotation) }
2. 修改已存在的墨迹注释线宽
如果是要修改PDF中已有的墨迹注释,只需要找到对应的PDFAnnotation对象,修改它的border.lineWidth即可:
// 遍历页面上的所有注释 if let page = pdfDocument.page(at: 0) { for annotation in page.annotations { if annotation.type == .ink { let border = annotation.border ?? PDFBorder() border.lineWidth = 10 // 修改为你需要的线宽 annotation.border = border } } } // 记得保存修改后的PDF文档 pdfDocument.write(to: outputURL)
关键说明
UIBezierPath的lineWidth仅用于PDFKit在本地绘制预览时的显示,不会被写入PDF文件,所以其他PDF阅读器打开时不会遵循这个值。PDFBorder的lineWidth才是真正存储在PDF注释字典中的属性,所有符合PDF规范的阅读器都会读取这个值来渲染墨迹的宽度。
内容的提问来源于stack exchange,提问作者Morpheus
相关产品推荐
相关产品推荐

