I’m trying to draw a custom string with color, font, size and alignment.
I got everything working with an NSMutableAttributedString before, but it looks like Text Aligment only works with Paragraph alignement which only works with non mutable version of NSString.
So, I had to change my previous code to this :
//Note : _name variables are provided by my GUI for text, size and font name.
//Create the String ColorRef
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
const CGFloat myColor[] = {_color.r/255.0, _color.g/255.0, _color.b/255.0, 1.0f};
CGColorRef colorRef = CGColorCreate(rgb, myColor);
//Setup paragraph Alignment Ref
CTTextAlignment theAlignment = kCTCenterTextAlignment;
CFIndex theNumberOfSettings = 1;
CTParagraphStyleSetting theSettings[1] = {{ kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &theAlignment }};
CTParagraphStyleRef theParagraphRef = CTParagraphStyleCreate(theSettings, theNumberOfSettings);
//Prep Font
NSDictionary *fontAttributes = [NSDictionary dictionaryWithObjectsAndKeys: _fontName, (NSString *)kCTFontFamilyNameAttribute,
[NSNumber numberWithFloat:_fontSize], (NSString *)kCTFontSizeAttribute,
nil];
CTFontRef font = [self newFontWithAttributes:fontAttributes];
//Prepare String Attributes
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: (id)font, (NSString *)kCTFontAttributeName,
[NSNumber numberWithFloat:_fontSize], (NSString *)kCTFontSizeAttribute,
(id)theParagraphRef, (NSString*)kCTParagraphStyleAttributeName,
colorRef, (NSString *)kCTForegroundColorAttributeName, nil];
//Create the Attributed String
NSAttributedString *myString = [[NSAttributedString alloc] initWithString:_textString
attributes: attributes];
But the Text Aligment still doesn’t work. Everything else is fine but text remains aligned on the Left.
Why ?
EDIT :
Each of my strings are created inside a class that is a subclass of CATextLayer. Each of those TextLayers are then added to a CALayer as sublayers. On updates I apply trasformation matrix on the sublayers and use setNeedsDisplay. This is how I display the text on screen. Maybe There’s a reason here why the CTParagraphStyleRef set is not working ?
I have no clues why the ParagraphStyle that I’ve set is not working, But I’ve found a solution that’s working for me, so I’m posting it in case someone encounter similar problems :
shown in my question.
self.alignmentMode = kCAAlignmentCenter;to alignthe text the way I want.
I’ve also found this very good guide on AttributedStrings that helped me improving my code and finding this solution.