来自 CoreText 的 attributedString 的 LineCount 是错误的

LineCount for attributedString from CoreText is wrong

来自 CoreText 基金会的属性字符串的行数似乎有误。我使用以下代码提取属性字符串中应存在的行数。

 - (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"\nMe and Me\n" attributes:nil];
    CGPathRef path = CGPathCreateWithRect(CGRectMake(0, 0, 335, 1000000), nil);
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attributedString);
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0,0), path, NULL);
    NSLog(@"%ld", numberOfLines(frame));


}

static CFIndex numberOfLines(CTFrameRef frame) {
    CGRect bounds = CGRectNull;
    CFArrayRef lines = CTFrameGetLines(frame);
    CFIndex numLines = CFArrayGetCount(lines);
    CGPoint *lineOrigins = malloc((numLines + 1) * sizeof(CGPoint));
    CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), lineOrigins);
    return numLines;
}

我预计要返回的行数等于三。一个用于第一个换行符,一个用于文本 "Me and Me",一个用于最后一个换行符。知道为什么它会返回 2 吗?

简单地使用普通定义,即一行为零个或多个字符以换行符终止

您可以将此行为与 Terminal 中的标准 wc(字数统计)命令 运行 进行比较。在您的示例文本中,它报告了 2 行、3 个单词和 11 个字符。在最后一个换行符和文件末尾之间添加字符会增加字数和字符数,但行数保持在 2。

HTH