How to use CGContext with AttributedString and image attachment

Using Swift 4, I draw NSMutableAttributedStringusing CGContextin a PDF file. The string contains an attachment with UIImage. But the image is lost when used UIGraphicsGetCurrentContext.

Creation NSMutableAttributedStringwith attachment:

let aString = NSMutableAttributedString()
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "miniatureIcon")!
aString.append( attachmentString )

Creating context.

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()

Since this is the last time the text is processed before it is drawn in the PDF file, and since I debugged it to this part where the attachment was last available, I assume that the error is part of the CGContext.

Other attributes, such as boldor center, remain in the final file. But the affection is gone.

What am I missing? Help is much appreciated.

+4
source share

Source: https://habr.com/ru/post/1690537/


All Articles