How to extract text string from a CTlineRef?

751 views Asked by At

How to extract text string from a CTlineRef ?

i know for example that i can do CTLineGetStringRange(aLine) and i have the AttributedString (ie: CFAttributedStringRef) that was used to generate the line. how to extract the text string from the AttributedString ?

1

There are 1 answers

0
rob mayoff On BEST ANSWER

So you have this:

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

Convert the CFRange to an NSRange and cast the CFAttributedStringRef to an NSAttributedString *:

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

Then you can use an Objective-C message to get the substring. If you want an attributed substring:

NSAttributedString *richSubtext = [richText attributedSubstringFromRange:nsRange];

If you want a plain substring:

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

If you want to stick with Core Foundation functions for some reason (I wouldn't recommend it), you can get the attributed substring:

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

Or the plain substring like this:

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