在iOS 11 PDFKit文档上实现墨迹注释

问题描述 投票:5回答:3

我想允许用户在PDFView中查看iOS 11 PDFKit文档。图纸最终应嵌入PDF中。

后者我通过向PDFPage添加类型为“ink”的PDFAnnotation来解决,其中UIBezierPath对应于用户的绘图。

但是,如何实际记录用户在PDFView上创建的触摸以创建这样的UIBezierPath?

我已经尝试在PDFView和PDFPage上覆盖touchesBegan,但它永远不会被调用。我试过添加一个UIGestureRecognizer,但没有做任何事情。

我假设我需要事后使用PDFView实例方法convert(_ point:CGPoint,to page:PDFPage)将获得的坐标转换为适合注释的PDF坐标。

ios pdf touch ios11
3个回答
3
投票

添加到jksoegaard的优秀答案,对像我这样的新手有一些澄清:

  1. 您需要在项目中包含UIBezierPath + .swift才能识别.moveCenter和rect.center。从https://github.com/xhamr/paintcode-path-scale下载。
  2. 可以排除这些行: UIGraphicsBeginImageContext(CGSize(width: 800, height: 600))

    let page = pdfView.page(for: position, nearest: true)!
  1. 您需要在函数之外声明一些全局变量: var signingPath = UIBezierPath() var annotationAdded : Bool? var lastPoint : CGPoint? var currentAnnotation : PDFAnnotation?
  2. 最后,如果你想要墨水更宽更好,你需要做两件事:

一个。每次在看到annotation.add或currentAnnotation.add之前,您需要(根据该函数的需要使用注释或currentAnnotation):

    let b = PDFBorder()
    b.lineWidth = { choose a pixel number here }
    currentAnnotation?.border = b
    currentAnnotation?.color=UIColor.{ your color of choosing }

我建议为颜色指定低alpha值。结果是美丽的,并受到你的中风速度的影响。例如,红色将是:

    UIColor(red: 255/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.1)

湾记录每次触摸的矩形需要适应较粗的线条。代替

    let rect = signingPath.bounds

尝试,以10px的厚度为例:

    let rect = CGRect(x:signingPath.bounds.minX-5, 
    y:signingPath.bounds.minY-5, width:signingPath.bounds.maxX- 
    signingPath.bounds.minX+10, height:signingPath.bounds.maxY- 
    signingPath.bounds.minY+10)

重要说明:touchesEnded函数也使用currentAnnotation变量。你必须在该函数中重复rect的定义(短的或上面提到的那个),并在那里重复currentAnnotation的定义:

    currentAnnotation = PDFAnnotation(bounds: rect, forType: .ink, withProperties: nil)

如果不这样做,一次没有移动的点击将使您的应用程序崩溃。

我可以验证一旦保存文件,就会保留注释。保存示例代码:

    let pdfData = pdfDocument?.dataRepresentation()
    let annotatedPdfUrl = URL(fileURLWithPath: "\ 
    (NSSearchPathForDirectoriesInDomains(.documentsDirectory, .userDomainMask, 
        true)[0])/AnnotatedPDF.pdf")
    try! pdfData!.write(to: annotatedPdfUrl)
© www.soinside.com 2019 - 2024. All rights reserved.