我正在尝试生成我的 UIView 的 pdf。在 View 中,我可以使用 CGContextSetBlendMode(context, CGBlendMode.Clear) 简单地删除行。虽然当我绘制到 pdf 上下文(使用 UIGraphicsBeginPDFContextToData 生成)时,这在 UIView 的上下文中正常工作,但相同的代码会生成与 CGContextSetStrokeColorWithColor 中设置的颜色相同的行。有人知道在 pdf 上下文中实现删除的替代方法吗?
例如,当我在 drawrect 的上下文下方运行代码时,它会生成一条微弱的红线 (alpha = 0.5),红线中有一个小间隙。但是,如果我提供 pdfcontext,它会变成一条微弱的红线,并有一条硬红线穿过它(因为叠加了另一条 alpha 0.5 的细红线)
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 10, 10)
CGPathAddLineToPoint(path, nil, 10,100)
CGContextAddPath(context, path)
CGContextSetLineCap(context, CGLineCap.Round)
CGContextSetStrokeColorWithColor(context, UIColor.redColor().colorWithAlphaComponent(0.5).CGColor)
CGContextSetLineWidth(context, 10.0)
CGContextStrokePath(context)
CGPathMoveToPoint(path, nil, 10, 10)
CGPathAddLineToPoint(path, nil, 10,100)
CGContextAddPath(context, path)
CGContextSetBlendMode(context, CGBlendMode.Clear)
CGContextSetLineWidth(context, 2.0)
CGContextStrokePath(context)
最佳答案
我最终通过变通方法解决了我的问题。为了其他任何有此问题的人的利益,这里开始。
我在 PDFContext 中单独绘制 subview 。对于每个我检查它是否包含删除。如果是这种情况,我会打开一个单独的 ImageContext 并生成一个 View 图像。
UIGraphicsBeginImageContext(objectView.frame.size)
if let imageContext = UIGraphicsGetCurrentContext() {
objectView.drawObjectInContext(imageContext,rect: objectView.bounds)
self.applyEraser(imageContext, eraserShape: objectView.eraserLayer.eraseShape)
let image = UIGraphicsGetImageFromCurrentImageContext()
CGContextTranslateCTM(pdfContext, 0, objectView.bounds.height)
CGContextScaleCTM(pdfContext, 1.0, -1.0)
CGContextDrawImage(pdfContext, objectView.bounds, image.CGImage)
}
UIGraphicsEndImageContext()
请注意,与 CGContext 中的常规绘图相比,图像是向上的,这就是我调用 CGContextTranslate en CGContextScale 的原因。
缺点是您在 PDF 中得到的是 subview 的图像,而不是简单的文本。但是,如果您分别为每个 View 执行此操作,则可以绘制 View 而无需将其正确删除为文本或任何您想要的内容。
关于swift - 在 pdf 上下文中删除线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33790923/