For a person like me, who is not familiar with working with CoreText most common tasks can be really painful. I hope this post saves you some time if you’re looking for information on how to set font and align your CFAttributedString. For text alignment you have to assign CTTextAlignment to CTParagraphStyle first and then set that CTParagraphStyle to your CFAttributedString. Setting font has more direct approach – CFAttributedString has special attribute for that.
In clearer terms aka code form:
// create attributed string
CFMutableAttributedStringRef attrStr = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
CFAttributedStringReplaceString (attrStr, CFRangeMake(0, 0), (CFStringRef) textString);
// create font
CTFontRef font = CTFontCreateWithName(CFSTR("Times New Roman"), 16, NULL);
// create paragraph style and assign text alignment to it
CTTextAlignment alignment = kCTJustifiedTextAlignment;
CTParagraphStyleSetting _settings[] = { {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment} };
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(_settings, sizeof(_settings) / sizeof(_settings[0]));
// set paragraph style attribute
CFAttributedStringSetAttribute(attrStr, CFRangeMake(0, CFAttributedStringGetLength(attrStr)), kCTParagraphStyleAttributeName, paragraphStyle);
// set font attribute
CFAttributedStringSetAttribute(attrStr, CFRangeMake(0, CFAttributedStringGetLength(attrStr)), kCTFontAttributeName, font);
// release paragraph style and font
CFRelease(paragraphStyle);
CFRelease(font);
Tags: CFAttributedString, CoreText, CTFontCreateWithName, CTParagraphStyle, CTTextAlignment
I’m not that much of a online reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back in the future. All the best
I am agree with you that view, I think it’s accurate, expressing feelings in my heart, said well, also my favorites were soccer shoes.
Yes it’s true, That is beneficial
Thank you very much! This helped a lot
Thank you so much. I spent hours trying to figure this out.
You just save me a lot of time… Thanks