我试图创建一个动画文本标签,突然这个奇怪的问题袭击了我。我正在尝试在视图上使用 CATextLayer 写出一个简单的标签。如您所见,我尝试使用 NSAttributedString 类的 sizeWithAttributes: 来计算文本的框架。即使我使用图层显示相同的属性字符串,这也会给出一个不完全适合 CATextLayer 的框架。
任何有关为什么会发生这种奇怪的字体渲染问题的见解都将不胜感激。
#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