在CGContext中绘制NSAttributedString时看起来很难看

时间:2009-04-03 21:17:40

标签: cocoa text core-animation pyobjc

我想在CoreAnimation图层中显示字符串,但遗憾的是CATextLayer还不够,主要是因为在使用约束来包装文本时很难使用它。

我正在使用NSLayoutManager,使用以下代码(PyObjC):

NSGraphicsContext.saveGraphicsState()

# THIS SOLVES THIS ISSUE
CGContextSetShouldSmoothFonts(ctx, False)

graphics = NSGraphicsContext.graphicsContextWithGraphicsPort_flipped_(ctx, True)
NSGraphicsContext.setCurrentContext_(graphics)

height = size.height
xform = NSAffineTransform.transform();
xform.translateXBy_yBy_(0.0, height)
xform.scaleXBy_yBy_(1.0, -1.0)
xform.concat()

self.textContainer.setContainerSize_(size)

glyphRange = self.layoutManager.glyphRangeForTextContainer_(self.textContainer)

self.layoutManager.drawBackgroundForGlyphRange_atPoint_(glyphRange, topLeft)
self.layoutManager.drawGlyphsForGlyphRange_atPoint_(glyphRange, topLeft)

NSGraphicsContext.restoreGraphicsState()

这一切都很好并且有效,但唯一的问题是它会产生看起来很糟糕的文本(尽管它 已经消除了腐蚀)。

以下是CATextLayer版本:

这是NSLayoutManager版本:

我缺少什么?

1 个答案:

答案 0 :(得分:16)

我正在回答这个问题,因为coretext-dev档案无法搜索,Apple的Aki Inoue刚回答了我的问题:

  

由于CALayer无法表示子像素颜色(也就是字体平滑),因此需要将其禁用。   我相信CATextLayer默认会这样做。

     

执行CGContextSetShouldSmoothFonts(context,false)。

谢谢,Aki!

Milen Dzhumerov的另一个评论:

  

我不相信这是准确的。我们使用亚像素消除锯齿将文本绘制到CALayers中。在绘制文本本身之前,您必须确保在文本后面绘制。有关参考资料,请参阅http://www.cocoabuilder.com/archive/message/cocoa/2008/3/28/202581

Milen是正确的,如果你事先知道背景颜色,你可以这样做:

CGContextSetRGBFillColor(ctx, r, g, b, a)
CGContextFillRect(ctx, (topLeft, size))
CGContextSetShouldSmoothFonts(ctx, True)

你会得到相当亚像素消除锯齿的文字。但是,如果知道背景颜色,则需要来关闭字体平滑,否则会出现乱码。

相关问题