如何从 CTlineRef 中提取文本字符串?

How to extract text string from a CTlineRef?

如何从 CTlineRef 中提取文本字符串?

例如,我知道我可以执行 CTLineGetStringRange(aLine) 并且我有用于生成该行的 AttributedString(即:CFAttributedStringRef)。如何从 AttributedString 中提取文本字符串?

所以你有这个:

CFAttributedStringRef cfAttributedString = ...;
CTLineRef line = ...;
CFRange cfRange = CTLineGetStringRange(line);

CFRange 转换为 NSRange 并将 CFAttributedStringRef 转换为 NSAttributedString *:

NSRange nsRange = NSMakeRange(cfRange.location, cfRange.length);
NSAttributedString *richText = (__bridge NSAttributedString *)cfAttributedString;

然后您可以使用 Objective-C 消息来获取子字符串。如果你想要一个属性子串:

NSAttributedString *richSubtext = [richText attributedSubstringFromRange:nsRange];

如果你想要一个普通的子串:

NSString *substring = [richText.string substringWithRange:nsRange];

如果你出于某种原因想要坚持使用 Core Foundation 函数(我不推荐它),你可以获得属性子字符串:

CFAttributedStringRef cfAttributedSubstring = CFAttributedStringCreateWithSubstring(
    NULL, cfAttributedString, cfRange);

或者像这样的普通子串:

CFStringRef cfString = CFAttributedStringGetString(cfAttributedString);
CFStringRef cfSubstring = CFStringCreateWithSubstring(NULL, cfString, cfRange);