使用 Swift 4,我正在使用
NSMutableAttributedString
绘制一个 CGContext
到 PDF 文件。该字符串包含带有 UIImage
的附件。但是使用UIGraphicsGetCurrentContext
.时图像会丢失
创建带有附件的
NSMutableAttributedString
:
let aString = NSMutableAttributedString()
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "miniatureIcon")!
aString.append( attachmentString )
创建上下文。
UIGraphicsBeginPDFPageWithInfo....
print("attributedString \(attributedString)") // attachement still here
// Get current graphics context
let currentContext = UIGraphicsGetCurrentContext()!
// Create a core text frame setter
let framesetter = CTFramesetterCreateWithAttributedString(attributedString)
// Save context pre manipulation
currentContext.saveGState()
// Reset text matrix, so no text scaling is affected
currentContext.textMatrix = CGAffineTransform.identity
// Create the frame and a rectangular path of the text frame
let frameRect = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
let framePath = UIBezierPath(rect: frameRect).cgPath
// Create core text frame for the given attributed string
// The whole text should fit the frame, as calculations were already done
let frameRef = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attributedString.length), framePath, nil)
// Translate by 100% graphics height up and reverse scale, as core text does draw from bottom up and not from top down
currentContext.translateBy(x: 0, y: UIGraphicsGetPDFContextBounds().height)
currentContext.scaleBy(x: 1.0, y: -1.0)
// Translate context to actual position of text
currentContext.translateBy(x: frame.minX, y: UIGraphicsGetPDFContextBounds().height - frame.maxY)
// Draw text into context
CTFrameDraw(frameRef, currentContext)
// Restore context to pre manipulation
currentContext.restoreGState()
UIGraphicsEndPDFContext()
由于这是在将文本绘制到 PDF 文件之前最后一次对其进行操作,并且由于我已将其调试到附件最后一次可用的这一部分,因此我假设该错误是 CGContext 的一部分.
其他属性如
bold
或 center
保留在最终文件中。
但是附件不见了。
我错过了什么?非常感谢帮助。