10

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

有什么我想念的吗?

4

1 回答 1

16

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

由于 CALayer 不能表示子像素颜色(又名字体平滑),您需要禁用它。我相信 CATextLayer 默认会这样做。

做 CGContextSetShouldSmoothFonts(context, false)。

谢谢,阿基!

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)

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

于 2009-04-03T21:24:18.383 回答