【发布时间】:2018-02-21 20:53:43
【问题描述】:
我只想使用 PDFKit 在 PDF 文件上绘图。这听起来很简单,但我遇到了很多麻烦。从文档中,墨水注释似乎适合于此。这是我的代码:
/// Adds a new annotation
func addAnnotation(color: UIColor, point: CGPoint) {
currentPage = pdfView.page(for: point, nearest: false)
// Here I convert the coordinates to the document and create a new annotation
if currentPage != nil {
let topRight = pdfView.convert(pdfView.frame.topRightCorner, to: currentPage!)
newAnnotation = PDFAnnotation(bounds: CGRect(origin: .zero, size: CGSize(width: topRight.x, height: topRight.y)), forType: .ink, withProperties: nil)
newAnnotation!.color = color
currentPage!.addAnnotation(newAnnotation!)
}
else {
newAnnotation = PDFAnnotation()
}
}
/// Adds a new path, maybe a new annotation
func addPath(color: UIColor, point: CGPoint, lineWidth: CGFloat) {
// Create annotation
if newAnnotation == nil {
addAnnotation(color: color, point: point)
}
guard currentPage != nil else { return }
let convertedPoint = pdfView.convert(point, to: currentPage!)
// Create initial path
let path = UIBezierPath()
path.lineWidth = 200
path.move(to: convertedPoint)
path.addLine(to: convertedPoint)
newAnnotation!.add(path)
}
/// Updates the last drawn annotation
func updatePath(point: CGPoint) {
if let annotation = newAnnotation, let page = currentPage {
let convertedPoint = pdfView.convert(point, to: page)
let lastPath = annotation.paths!.last!
lastPath.addLine(to: convertedPoint)
annotation.remove(lastPath)
annotation.add(lastPath)
}
}
我的主要问题是性能。我编写所有这些代码只是为了拥有一个功能绘图程序。我在这个过程中所理解的:
- 将注释中的路径分组而不是每个路径有一个注释似乎更有效。所以我添加了 addAnnotation() 方法,它有时会创建一个新的注解。
- 创建注释时的'bounds' 属性对性能有很大影响。将此属性设置为页面的边界会使程序非常慢。但问题是,在用户完成绘制之前我不知道注释的边界......
-
我有一个方法 touchMoved(),我想在路径中添加一个点。起初,我只是在做:
if let annotation = newAnnotation, let page = currentPage { let convertedPoint = pdfView.convert(point, to: page) let lastPath = annotation.paths!.last! lastPath.addLine(to: convertedPoint) }
但路径没有更新,所以我添加了以下行:
annotation.remove(lastPath)
annotation.add(lastPath)
事实证明这在性能方面非常糟糕(路径有时会消失,然后再出现)。
我假设有更好的方法来做这一切,但我找不到任何好的例子。如果您在 PDFKit 上有一个 Ink 注释的工作示例,那也很棒。
附带问题:在我的代码中,我将 bezierPath 的 lineWidth 设置为 200。这是因为我想更改注释的 lineWidth,但更改 bezierPath 的 lineWidth 似乎并没有改变任何东西。有什么想法吗?
【问题讨论】:
标签: ios annotations pdfkit