CGContext.makeImage生成的文本图像与原文本不匹配求助
文本转图像后与原文本无法完全匹配的解决方案求助
我需要用文本创建蒙版,需将文本转换为图像,但转换后发现其与原文本无法完全匹配。为此我进行了如下测试:
class MyView: NSView{ override func draw(_ dirtyRect: NSRect) { guard let g = NSGraphicsContext.current?.cgContext else{ return } let antialiasing = false //true or false is useless g.setAllowsAntialiasing(antialiasing) g.setShouldAntialias(antialiasing) let text: NSString = "HELLO" let pos: CGPoint = .init(x: 20, y: 20) let font: NSFont = .init(name: "Arial Black", size: 96)! var textAttr: [NSAttributedString.Key: Any] = [ .font : font ] // 在新CGContext中绘制蓝色文本,生成图像后绘制到当前CGContext let image = createImage(dirtyRect: dirtyRect) { g in g.setAllowsAntialiasing(antialiasing) g.setShouldAntialias(antialiasing) textAttr[.foregroundColor] = NSColor.blue text.draw(at: pos, withAttributes: textAttr) } g.draw(image!, in: dirtyRect, byTiling: false) // 使用相同属性绘制黄色文本 let attr: [NSAttributedString.Key: Any] = [ .font : font, .foregroundColor : NSColor.yellow ] text.draw(at: pos, withAttributes: attr) } private func createImage(dirtyRect: NSRect, drawingHandler: ((_ g: CGContext) -> Void)?) -> CGImage?{ NSGraphicsContext.saveGraphicsState() let g = CGContext(data: nil, width: Int(dirtyRect.width), height: Int(dirtyRect.height), bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! NSGraphicsContext.current = NSGraphicsContext(cgContext: g, flipped: false) drawingHandler?(g) let image = g.makeImage() NSGraphicsContext.restoreGraphicsState() return image } }
可以看到,叠加后的两段文本无法完全重合,下方的蓝色文本露出一圈边缘。
我尝试了其他createImage方法,比如创建NSImage并在其上绘制文本,或创建CGLayer绘制文本后生成图像,结果类似。
唯一完美的解决方案是使用当前CGContext并禁用抗锯齿来生成文本图像,但该方法生成的图像会包含所有绘制内容,其中部分内容并非我所需:
private func createImage(dirtyRect: NSRect, drawingHandler:((_ g: CGContext) -> Void)?) -> CGImage?{ drawingHandler?(NSGraphicsContext.current!.cgContext) return NSGraphicsContext.current?.cgContext.makeImage() }
请问有什么可行的解决方案?谢谢。

内容的提问来源于stack exchange,提问作者Mandroid
相关产品推荐
相关产品推荐

