Ugly looking text when drawing NSAttributedString in CGContext

后端 未结 1 677
轮回少年
轮回少年 2020-12-16 02:26

I want to display strings inside CoreAnimation layers, but unfortunately CATextLayer is not enough, mostly because it\'s difficult to use when using constraints and

相关标签:
1条回答
  • 2020-12-16 02:57

    I'm answering this because the coretext-dev archives are not searchable, and Aki Inoue from Apple just answered my question:

    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).

    Thanks, Aki!

    Another comment by 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 http://www.cocoabuilder.com/archive/message/cocoa/2008/3/28/202581 for references.

    Milen is correct, in case you know the background colour beforehand, you can do:

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

    And you get pretty sub-pixel anti-aliased text. However, if you don't know the background colour, you need to turn off font smoothing or you'll get garbled results.

    0 讨论(0)
提交回复
热议问题