如何使用子像素渲染绘制文本,如NSString draw(in:withAttributes :)?

时间:2017-10-21 20:59:03

标签: macos cocoa nsstring nsview

我有一些使用NSTextField的Cocoa视图,他们使用系统的子像素渲染设置:

NSTextField 3

我有一些覆盖draw(_:)的其他自定义Cocoa视图,并使用NSString draw(in:withAttributes:)等方法绘制文本,而这些视图从不使用子像素渲染:

NSString draw() 3

它看起来并不糟糕,但看起来确实不同,我希望我的所有文字看起来都一样。

我的样本绘制方法非常简单:

override func draw(_ dirtyRect: NSRect) {
    let attrs: [String: Any] = [
        NSFontAttributeName: NSFont.labelFont(ofSize: 12),
    ]
    "3".draw(in: bounds, withAttributes: attrs)
}

我在draw()方法的顶部尝试了所有我能找到的与子像素渲染相关的内容:

let ctx = NSGraphicsContext.current()!.cgContext
ctx.setShouldSubpixelPositionFonts(true)
ctx.setShouldSubpixelQuantizeFonts(true)
ctx.setAllowsFontSubpixelPositioning(true)
ctx.setAllowsFontSubpixelQuantization(true)
ctx.setAllowsAntialiasing(true)
ctx.setAllowsFontSmoothing(true)
ctx.setShouldAntialias(true)
ctx.setShouldSmoothFonts(true)  // (this works, but only if the background is opaque)

但它们没有效果。也许我不明白图形上下文是如何工作的。

如果没有实例化NSTextField,如何使用子像素渲染绘制文本?

0 个答案:

没有答案