我在iOS上使用PDFKit突出显示文本(PDF文件)。我通过创建PDFAnnotation并将其添加到选定的文本区域来实现。我想精确地突出显示所选区域,但它始终覆盖整行,如下图所示。如何仅为选定区域创建注释?
我的代码:
let highlight = PDFAnnotation(bounds: selectionText.bounds(for: page), forType: PDFAnnotationSubtype.highlight, withProperties: nil) highlight.color = highlightColor page.addAnnotation(highlight)
PDFSelection bounds(forPage:)方法返回一个矩形以满足整个选择区域。不是您情况下的最佳解决方案。
PDFSelection
bounds(forPage:)
尝试使用selectionsByLine(),并为每个矩形添加单独的注释,以表示PDF中的每个选定行。例:
selectionsByLine()
let selections = pdfView.currentSelection?.selectionsByLine() // Simple scenario, assuming your pdf is single-page. guard let page = selections?.first?.pages.first else { return } selections?.forEach({ selection in let highlight = PDFAnnotation(bounds: selection.bounds(for: page), forType: .highlight, withProperties: nil) highlight.endLineStyle = .square highlight.color = UIColor.orange.withAlphaComponent(0.5) page.addAnnotation(highlight) })