Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

ios - Wrong highlight annotation on apple PDFKit

I'm using PDFKit on iOS to highlight texts (PDF file). I do it by create a PDFAnnotation and add it to the selected text area. I want to highlight precisely the selected area but it always covers the whole line like the pics below. How can I create the annotation for the selected area only??

My code:

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

Selected text

Highlighted text

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

PDFSelection bounds(forPage:) method returns one rectangle to satisfy whole selection area. Is not the best solution in your case.

Try with selectionsByLine(), and add individual annotation for every rect, representing every single selected line in PDF. Example:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...