Search code examples
iosswiftannotationstouchpdfkit

Annotating PDFs with different coordinate systems


I am drawing a line on a pdf using PDFKIT. I override touches began, moved etc as below to log my touches on the pdfView's documentView as follows:

 override func touchesMoved(_ touches: Set<UITouch>,
                           with event: UIEvent?) {
    // 6
    swiped = true
    if let touch = touches.first {
        let currentPoint = touch.location(in: pdfView.documentView)
       drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)
        addAnnotation(fromPoint: lastPoint, toPoint: currentPoint)

        // 7
        lastPoint = currentPoint

    }
}

However, as you can see from my image below (the black line is where I touch the screen and the red line is where the annotation is drawn). The touches coordinate system is (0,0) at the top left of the screen and the pdf is annotated from the bottom left (0,0) of the screen.

iPad image inserted

My add annotation function is as follows:

func addAnnotation(fromPoint: CGPoint, toPoint: CGPoint) {

    let page = pdfView.document?.page(at: 0)
    let bounds = CGRect(x: 0, y: 0, width: 600, height: 600)
    let line = PDFAnnotation(bounds: bounds, forType: .line, withProperties: nil)
    line.startPoint = fromPoint
    line.endPoint = toPoint
    line.startLineStyle = .none
    line.endLineStyle = .none
    line.color = .red

    let border = PDFBorder()
    border.lineWidth = 4.0
    line.border = border
    page?.addAnnotation(line)
}

How can I align the coordinate systems so the place I touch on screen is where the annotation is drawn?


Solution

  • For those that are interested, I solved this one by using the following function that comes with the framework that converts a point from view space to page space.

    func convert(_ point: CGPoint, to page: PDFPage) -> CGPoint
    

    Hopefully, this will help some of you.