cocoa – 在CGContext中绘制NSAttributedString时看起来很难看的文本

前端之家收集整理的这篇文章主要介绍了cocoa – 在CGContext中绘制NSAttributedString时看起来很难看的文本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在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版本:http://i39.tinypic.com/23h0h1d.png

这是NSLayoutManager版本:http://i40.tinypic.com/2vv9rw5.png

我错过了什么?

解决方法

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

Since CALayer cannot represent subpixel color (aka font smoothing),you need to disable it.
I believe CATextLayer does it by default.

Do CGContextSetShouldSmoothFonts(context,false).

谢谢,Aki!

Milen Dzhumerov的另一个评论

I don’t believe this is accurate. We’re drawing text into CALayers with subpixel anti-aliasing. You just have to make sure that you’ve drawn behind the text before drawing the text itself. See 07000 for references.

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

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

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

原文链接:https://www.f2er.com/html/231776.html

猜你在找的HTML相关文章