如何让CATextLayer平滑其文本?

ale*_*ail 8 macos core-animation objective-c antialiasing subpixel

根据文档,可以在CATextLayer中启用字体平滑:

Text can only be drawn using sub-pixel antialiasing when it is composited into an existing opaque background at the same time that it's rasterized.

这是我理解这句话的方式:

@implementation CATextLayerWithFontSmoothing
-(id)init {
    self=[super init];
    if (self) {
    CALayer * whiteBackground = [CALayer layer];
    CATextLayer * blackText = [CATextLayer layer];

    [whiteBackground setBounds:NSMakeRect(0, 0, 300, 300)];
    [blackText setBounds:NSMakeRect(0, 0, 300, 300)];

    [whiteBackground setBackgroundColor:[NSColor whiteColor].CGColor];
    [blackText setForegroundColor:[NSColor blackColor].CGColor];
    [blackText setString:@"CATextLayer"];

    [blackText setShouldRasterize:YES];

    [self addSublayer:whiteBackground];
    [self addSublayer: blackText];

    }
    return self;
Run Code Online (Sandbox Code Playgroud)

这不起作用.不使用子像素消除锯齿绘制文本.

ale*_*ail 8

这里描述的方法有效:

案例2:如果您直接使用CATextLayer,则需要继承CATextLayer并在绘图代码中执行以下操作:

- (void)drawInContext:(CGContextRef)ctx
{
CGContextSetRGBFillColor (ctx, r, g, b, a);
CGContextFillRect (ctx, [self bounds]);
CGContextSetShouldSmoothFonts (ctx, true);
[super drawInContext:ctx];
}
Run Code Online (Sandbox Code Playgroud)

以下是平滑与非平滑的比较:

常规CATextLayer上的文本

带有子像素aa的文本

两层的800%缩放

PS:不要在CRT上看这个答案.