How to work around poor text rendering in text backed by a CALayer

前端 未结 4 1827
感动是毒
感动是毒 2021-01-31 23:16

I have some variable text in an NSTextField that renders on a CALayer background view. As a CALayer does not support sub-pixel aliasing fo

4条回答
  •  一整个雨季
    2021-01-31 23:41

    I'm not quite sure what your limitations are, or why you absolutely have to draw to a layer, but new in os4.1 among other things, Core Text was ported to iOS from the desktop. You can probably take advantage of it's advanced type setting features to render glyphs along lines or even arcs and have it do most of the heavy lifting for you. It is a relatively low-level API, but it is very fast.

    - (void)drawLayer:(CALayer *)theLayer
            inContext:(CGContextRef)context
    {
        CFStringRef string; CTFontRef font;  // assuming these exist
    
        // Initialize string, font, and context
        CFStringRef keys[] = { kCTFontAttributeName };
        CFTypeRef values[] = { font };
    
        CFDictionaryRef attributes =
            CFDictionaryCreate(kCFAllocatorDefault, (const void**)&keys,
                (const void**)&values, sizeof(keys) / sizeof(keys[0]),
                &kCFTypeDictionaryCallBacks,
                &kCFTypeDictionaryValueCallbacks);
    
        CFAttributedStringRef attrString =
            CFAttributedStringCreate(kCFAllocatorDefault, string, attributes);
        CFRelease(string);
        CFRelease(attributes);
    
        CTLineRef line = CTLineCreateWithAttributedString(attrString);
    
        // Set text position and draw the line into the graphics context
        CGContextSetTextPosition(context, 10.0, 10.0);
        CTLineDraw(line, context);
        CFRelease(line);
    }
    

    Other examples include CoreTextArcCocoa and CoreTextTest

提交回复
热议问题