我正在使用带有子类型墨水的 PDFAnnotation() 类向 PDFDocument 添加墨水注释。这个想法是捕获使用触摸绘制的签名。
受 UberSignature 的启发,我的 UIBezierPath 是一系列应该填充颜色的矩形。但是,当我将注释添加到 PDFDocument 时,它没有被填充。
似乎 UIBezierPath 的 fill() 方法在添加到 PDFAnnotation 时什么都不做?
如果我使用相同的 UIBezierPath 并将其绘制在 UIImage 上,它会正确填充纯色。
有什么可能出错的想法吗?
有问题的代码:
UIColor.red.setStroke()
UIColor.red.setFill()
var path = UIBezierPath()
path.append(myRectangles)
path.fill()
var annotation = PDFAnnotation(bounds: path.bounds, forType: .ink, withProperties: nil)
annotation.add(path)
myPDFPage.addAnnotation(annotation)
在屏幕截图中,我尝试编写普通文本和两个示例行。左边的线画得慢,右边的线画得快。这个想法是让线条的宽度根据绘制的速度而变化,以使签名看起来更自然/逼真。
最佳答案
我设法找到了一个看起来相对最优的问题解决方案。
诀窍是创建 PDFAnnotation 的子类并覆盖 draw(with box:, in context:) 函数。在这个函数中,我可以使用 drawPath(using: .fill) 方法来填充贝塞尔曲线路径。
代码可以是这样的:
class SignatureAnnotation : PDFAnnotation {
public var myPath : UIBezierPath = UIBezierPath()
override func draw(with box: PDFDisplayBox, in context: CGContext) {
context.saveGState()
self.page?.transform(context, for: box)
context.beginPath()
context.setLineWidth(0.1)
context.setShouldAntialias(true)
context.addPath(self.myPath.cgPath.mutableCopy()!)
context.drawPath(using: .fill)
context.restoreGState()
}
}
将此注释(类型 .stamp)添加到 PDF 而不是墨迹注释,所有内容都将呈现为矢量(完全可缩放而不会被像素化)- 并且在保存到文件时将与 PDF 的其余部分一起保存或数据缓冲区。
唯一的缺点是 UIBezierPath 不能太复杂,因为如果 draw() 函数耗时太长会引入闪烁。这可以通过简单地将 UIBezierPath 拆分为多个单独的路径来解决,每个路径都有自己的注释。
关于iOS 11 PDFKit Ink 注释 - 无法填充 UIBezierPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49041027/