相关疑难解决方法(0)

行间距如何在Core Text中工作?(为什么它与NSLayoutManager不同?)

我正在尝试使用Core Text函数绘制文本,其行间距尽可能接近使用NSTextView时的行间距.

以此字体为例:

NSFont *font = [NSFont fontWithName:@"Times New Roman" size:96.0];
Run Code Online (Sandbox Code Playgroud)

如果我在NSTextView中使用它,这个字体的行高是111.0.

NSLayoutManager *lm = [[NSLayoutManager alloc] init];
NSLog(@"%f", [lm defaultLineHeightForFont:font]); // this is 111.0
Run Code Online (Sandbox Code Playgroud)

现在,如果我使用Core Text做同样的事情,结果是110.4(假设您可以通过添加上升,下降和前导来计算线高).

CTFontRef cFont = CTFontCreateWithName(CFSTR("Times New Roman"), 96.0, NULL);
NSLog(@"%f", CTFontGetDescent(cFont) + CTFontGetAscent(cFont) + 
             CTFontGetLeading(cFont)); // this is 110.390625
Run Code Online (Sandbox Code Playgroud)

这非常接近111.0,但对于某些字体,差异要大得多.例如,对于Helvetica,NSLayoutManager给出115.0而CTFont上升+下降+领先= 96.0.很明显,对于Helvetica,我无法使用上升+下降+导致计算线之间的间距.

所以我想我会使用CTFrame和CTFramesetter来布局几行并从中获取行间距.但这也给出了不同的价值观.

CTFontRef cFont = CTFontCreateWithName(CFSTR("Times New Roman"), 96.0, NULL);
NSDictionary *attrs = [NSDictionary dictionaryWithObject:(id)cFont forKey:(id)kCTFontAttributeName];
NSAttributedString *threeLines = [[NSAttributedString alloc] initWithString:@"abcdefg\nabcdefg\nabcdefg" attributes:attrs];

CTFramesetterRef threeLineFramesetter =  CTFramesetterCreateWithAttributedString((CFAttributedStringRef)threeLines);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0.0, …
Run Code Online (Sandbox Code Playgroud)

macos objective-c nslayoutmanager nstextview core-text

26
推荐指数
1
解决办法
1万
查看次数