使用 Swift 在位图图形上下文(在 macOS 上)中添加文本

Jea*_*rre 6 macos core-graphics bitmap cgcontext swift

我的项目是

\n\n
    \n
  1. 将一些图像裁剪粘贴到位图图形上下文上
  2. \n
  3. 添加一些文本
  4. \n
  5. 将位图另存为 JPEG 图像
  6. \n
\n\n

我对 1) 和 3) 没有问题,但我可以 \xe2\x80\x99t 找到一种将文本添加到位图图形上下文的方法。我花了很多时间阅读一些帖子,但没有成功。\n文档(https://developer.apple.com/reference/coregraphics/cgcontext/1586505-showtextatpoint)说我应该考虑核心文本,但我\n不知道如何应该使用 Core Text 将一些文本添加到我的\n位图上下文中。我还读到 NSString 的绘制实例方法允许\n在当前图形上下文中写入文本,但据我所知当前\n图形上下文与我的位图图形上下文无关?

\n\n

需要明确的是,我对在屏幕上绘制文本不感兴趣,我感兴趣的是在位图中绘制文本并将该位图保存在文件中。

\n\n
let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()\n// Create the bitmap graphic context\nvar gc = CGContext(data: nil, width: 400, height: 400, bitsPerComponent: 8, bytesPerRow: 0,\n                   space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue)\n\n// draw an image (croppedCGImage is a CGImage instance)\nvar rect = CGRect(x: 0, y:0, width:200, height: 200)\ngc?.draw(croppedCGImage, in: rect)\n\n// draw some text ????\n// how to do that ?\n\n// make a new CGImage\nlet newImage = gc!.makeImage()\n
Run Code Online (Sandbox Code Playgroud)\n\n

谢谢你帮助我!

\n