苹果PDFKit错误的高亮注释

时间:2017-11-24 08:51:57

标签: ios swift pdf pdfkit

我在iOS上使用PDFKit来突出显示文本(PDF文件)。我是通过创建PDFAnnotation并将其添加到选定的文本区域来完成的。我想要精确地突出显示所选区域,但它总是覆盖整个线条,如下图所示。如何仅为选定区域创建注释?

我的代码:

        let highlight = PDFAnnotation(bounds: selectionText.bounds(for: page), forType: PDFAnnotationSubtype.highlight, withProperties: nil)
        highlight.color = highlightColor
        page.addAnnotation(highlight)

Selected text

Highlighted text

2 个答案:

答案 0 :(得分:3)

PDFSelection bounds(forPage:)方法返回一个矩形以满足整个选择区域。在您的情况下,这不是最好的解决方案。

尝试使用selectionsByLine(),并为每个矩形添加单个注释,表示PDF中的每个选定行。例如:

    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)
    })

答案 1 :(得分:0)

根据PDFKit Highlight Annotation: quadrilateralPoints中的建议,您可以使用quadrilateralPoints将不同的行高亮添加到同一注释中。

func highlight() {  
    guard let selection = pdfView.currentSelection, let currentPage = pdfView.currentPage else {return}
    let selectionBounds = selection.bounds(for: currentPage)
    let lineSelections = selection.selectionsByLine()

    let highlightAnnotation = PDFAnnotation(bounds: selectionBounds, forType: PDFAnnotationSubtype.highlight, withProperties: nil)

    highlightAnnotation.quadrilateralPoints = [NSValue]()
    for (index, lineSelection) in lineSelections.enumerated() {
        let n = index * 4
        let bounds = lineSelection.bounds(for: pdfView.currentPage!)
        let convertedBounds = bounds.convert(to: selectionBounds.origin)
        highlightAnnotation.quadrilateralPoints?.insert(NSValue(cgPoint: convertedBounds.topLeft), at: 0 + n)
        highlightAnnotation.quadrilateralPoints?.insert(NSValue(cgPoint: convertedBounds.topRight), at: 1 + n)
        highlightAnnotation.quadrilateralPoints?.insert(NSValue(cgPoint: convertedBounds.bottomLeft), at: 2 + n)
        highlightAnnotation.quadrilateralPoints?.insert(NSValue(cgPoint: convertedBounds.bottomRight), at: 3 + n)
    }

    pdfView.currentPage?.addAnnotation(highlightAnnotation)
}

extension CGRect {

    var topLeft: CGPoint {
        get {
            return CGPoint(x: self.origin.x, y: self.origin.y + self.height)
        }
    }

    var topRight: CGPoint {
        get {
            return CGPoint(x: self.origin.x + self.width, y: self.origin.y + self.height)
        }
    }

    var bottomLeft: CGPoint {
        get {
            return CGPoint(x: self.origin.x, y: self.origin.y)
        }
    }

    func convert(to origin: CGPoint) -> CGRect {
        return CGRect(x: self.origin.x - origin.x, y: self.origin.y - origin.y, width: self.width, height: self.height)
    }
}