swift - 在 pdf 上下文中删除线条

标签 swift uiview pdf-generation quartz-graphics erase

我正在尝试生成我的 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/

相关文章:

java - "PDF"场景当前发展的良好来源是什么?

c# - iTextPdf 如何分页

.net - 部署到服务器上的 IIS 后,Rotativa pdf 无法工作

arrays - 如何在 Swift 中按属性值对自定义对象数组进行排序

objective-c - 随着 uiimageview 的旋转调整 uiview 的大小

ios - 如何通过单击按钮以编程方式增加自定义 uiview 及其在 View Controller 中的所有 subview 的宽度

ios - 如何将 subview 大小调整传播到父 View 大小调整?

ios - JSON 解析,嵌套 JSON 结构问题

macos - 在 Swift 中执行 TCP/IP 网络 I/O

swift - UICollectionViewCompositionalLayout 中的动态项目计数可能吗?