使用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
等其他属性仍保留在最终文件中。
但是附件已经消失了。
我错过了什么?非常感谢帮助。