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

问题描述 投票:9回答:1

我想在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版本:

我缺少什么?

cocoa text core-animation pyobjc
1个回答
16
投票

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

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

做CGContextSetShouldSmoothFonts(context,false)。

谢谢,Aki!

Anotner的评论是Milen Jumerov:

我不相信这是准确的。我们使用亚像素消除锯齿将文本绘制到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)

而你得到漂亮的亚像素抗锯齿文本。但是,如果您不知道背景颜色,则需要关闭字体平滑,否则会出现乱码结果。

© www.soinside.com 2019 - 2024. All rights reserved.