【问题标题】:Erasing lines in pdf context在pdf上下文中擦除线条
【发布时间】:2015-11-18 21:39:07
【问题描述】:

我正在尝试生成我的 UIView 的 pdf。在视图中,我可以使用 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)

【问题讨论】:

    标签: swift uiview pdf-generation quartz-graphics erase


    【解决方案1】:

    我最终通过解决方法解决了我的问题。为了其他有此问题的人的利益,这里是。

    我在 PDFContext 中单独绘制子视图。对于每个我检查它是否包含擦除。如果是这种情况,我会打开一个单独的 ImageContext 并生成视图的图像。

    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 和 CGContextScale 的原因。

    缺点是您会在 PDF 中获得子视图的图像,而不是简单的文本。但是,如果您分别为每个视图执行此操作,则可以绘制视图而无需正确擦除为文本或您想要的任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      相关资源
      最近更新 更多