CoreText: set text font and alignment to CFAttributedString

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: , , , ,

6 responses

  1. Posted January 29, 2011 at 20:06 | Permalink

    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

  2. Posted April 12, 2011 at 05:12 | Permalink

    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.

  3. *
    Posted February 26, 2012 at 05:40 | Permalink

    Yes it’s true, That is beneficial

  4. Lorenzo
    Posted May 23, 2012 at 10:07 | Permalink

    Thank you very much! This helped a lot ;)

  5. MoleFole
    Posted May 29, 2012 at 02:09 | Permalink

    Thank you so much. I spent hours trying to figure this out.

  6. amat
    Posted April 18, 2013 at 09:34 | Permalink

    You just save me a lot of time… Thanks ;)

Leave a Reply