Adding text to a bitmap graphics context (on macOS) with Swift

My project

  • for inserting some graphics cultures into a raster graphics context
  • add text
  • to save the bitmap as a JPEG image

I have no problem for 1) and 3), but I can't find a way to add text to the bitmap graphics context. I have been reading some of the posts for many hours without success. The doc ( https://developer.apple.com/reference/coregraphics/cgcontext/1586505-showtextatpoint ) says that I should consider Core Text, but I have no idea how I should use Core Text to add some text to mine raster context. I also read that the niche NSString instance method allows for text to be written in the current graphics context, but AFAIK - the current graphics context is not associated with my bitmap graphics context?

To be clear, I am not interested in drawing text on the screen, I am interested in drawing text in my bitmap and saving that bitmap in a file.

let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()
// Create the bitmap graphic context
var gc = CGContext(data: nil, width: 400, height: 400, bitsPerComponent: 8, bytesPerRow: 0,
                   space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue)

// draw an image (croppedCGImage is a CGImage instance)
var rect = CGRect(x: 0, y:0, width:200, height: 200)
gc?.draw(croppedCGImage, in: rect)

// draw some text ????
// how to do that ?

// make a new CGImage
let newImage = gc!.makeImage()

      

Thanks for helping me!

+3


source to share





All Articles