Sam*_*Sam 1 cocoa objective-c calayer swift
使用 Cocoa (OS X) 绘制的文本CALayer显示为CATextLayer颗粒状。必须使用什么方法/途径才能使文本清晰/清晰?
我很高兴文本有不透明的背景支持- 我知道如果需要透明,问题会更加复杂。
我无法使用NSView 派生实例(如 NSTextField)来表示解决方案中的文本 - 我使用 CALayer 因为它更轻量级。
编辑
我正在根据以下评论使用我尝试过的代码进行更新:
以下是一个自定义 CATextLayer 类,其中背景颜色在与文本组合之前被预设为不透明,以便可以发生子像素抗锯齿:
class TextLayer: CATextLayer {
override func drawInContext(ctx: CGContext!) {
CGContextSaveGState(ctx)
CGContextSetRGBFillColor (ctx, 1, 1, 1, 1)
CGContextFillRect (ctx, self.bounds)
CGContextSetShouldSmoothFonts (ctx, true)
super.drawInContext(ctx)
CGContextSaveGState(ctx)
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在自定义视图中使用此自定义派生 CATextLayer,如下所示:
override func awakeFromNib() {
self.wantsLayer = true
var backingLayer = self.layer
var textLayer = TextLayer()
textLayer.string = "ABC"
textLayer.fontSize = 16
textLayer.foregroundColor = NSColor.blackColor().CGColor
textLayer.frame = NSMakeRect(0, 0, 80, 40)
backingLayer?.addSublayer(textLayer)
textLayer.setNeedsDisplay()
}
Run Code Online (Sandbox Code Playgroud)
最终结果是我的视网膜 MacBook Pro 上的图片仍然有颗粒感。
在 CALayer 上尝试一些属性得出了解决方案......
为了使上面的代码能够在视网膜 Mac 上平滑地渲染字体并与其他字体保持一致,您似乎还需要设置:
textLayer.contentsScale = 2.0
Run Code Online (Sandbox Code Playgroud)
在 NSView 子类中。
我的理解是,这会从底层图像生成更详细的位图,与支持 Retina 的硬件更匹配。