Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paragraph justify with CoreText

I have the following code to format a paragraph of text with CoreText.

(...)

CTFontRef fontRef = CTFontCreateWithName((CFStringRef)fontName,
                                         [self.fontSize floatValue], NULL);

CTTextAlignment alignment = kCTJustifiedTextAlignment;

CTParagraphStyleSetting settings[]={
    {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment},
};

CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, 
                                           sizeof(settings)/sizeof(settings[0]));

self.attrs = [NSDictionary dictionaryWithObjectsAndKeys:
         //The following line doesn't work!
         (id)paragraphStyle, kCTParagraphStyleAttributeName,
         (id)self.color.CGColor, kCTForegroundColorAttributeName,
         (id)fontRef, kCTFontAttributeName,
         nil];

CFRelease(fontRef);
CFRelease(paragraphStyle);

NSMutableAttributedString* aString = [[[NSMutableAttributedString alloc] initWithString:@""] autorelease];

(...)

[aString appendAttributedString:[[[NSAttributedString alloc] initWithString:text attributes:attrs] autorelease]];

If I remove the following attribute pair (value/key), everything works (color, font, etc.).

(id)paragraphStyle, (NSString*)kCTParagraphStyleAttributeName,

If I put this attribute on attrs dictionary, the program enters on an infinite loop when I use CTFrameGetVisibleStringRange.

What I'm doing wrong?


UPDATE: After Mattias answer I figured out that the code wasn't the problem. There were some HTML tags lost in the middle of the text (garbage) and for some reason the FrameSetter was getting lost and returning and empty range. When there's no HTML tags on text everything went ok.

like image 382
javsmo Avatar asked Feb 11 '26 09:02

javsmo


1 Answers

I would suspect that CTParagraphStyleCreate returns NULL for some reason causing dictionaryWithObjectsAndKeys: to create an empty dictionary. But I can't see any error with your paragraph style setting.

Take a look at my CoreTextLabel.m class source which uses paragraph style settings.

like image 163
Mattias Wadman Avatar answered Feb 13 '26 22:02

Mattias Wadman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!