CATextLayer字形被剪裁或切断

时间:2013-05-24 22:41:57

标签: macos core-animation calayer nsattributedstring catextlayer

我试图创建一个动画文字标签,突然间这个奇怪的问题袭击了我。我试图在视图上使用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

1 个答案:

答案 0 :(得分:0)

CATextLayer使用CoreText渲染字形而不是Cocoa(基于实验的有根据的猜测)。

查看此示例代码,了解如何使用CoreText和CTTypesetter计算大小。这给了我们更准确的结果: https://github.com/rhult/height-for-width