I was trying to create an animated text label and suddenly this odd problem hit me. I am trying to write out a simple label using CATextLayer on a view. As you can see, I have tried to calculate the frame of the text by using the sizeWithAttributes: of the NSAttributedString class. This gives out a frame that doesn't perfectly fit the CATextLayer even though I am displaying the same attributed string using the layer.
Any insights into why this odd font-rendering problem is happening would be appreciated.
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize view;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
view.layer = [CALayer layer];
[view setWantsLayer:YES];
CATextLayer *textLayer = [CATextLayer layer];
textLayer.fontSize = 12;
textLayer.position = CGPointMake(100, 50);
[view.layer addSublayer:textLayer];
NSFont *font = [NSFont fontWithName:@"Helvetica-Bold" size:12];
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
NSString *helloString = @"This is a long string";
NSAttributedString *hello = [[NSAttributedString alloc] initWithString:helloString attributes:attrs];
NSSize stringBounds = [helloString sizeWithAttributes:attrs];
stringBounds.width = ceilf(stringBounds.width);
stringBounds.height = ceilf(stringBounds.height);
textLayer.bounds = CGRectMake(0, 0, stringBounds.width, stringBounds.height);
textLayer.string = hello;
}
@end