我正在尝试使用颜色、字体、大小和对齐方式绘制自定义字符串。
我之前使用 NSMutableAttributedString 进行了所有工作,但看起来文本对齐仅适用于段落对齐,它仅适用于非可变版本的 NSString。
所以,我不得不将我以前的代码更改为:
//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];
但是文本对齐仍然不起作用。其他一切都很好,但文本保持在左侧对齐。
为什么 ?
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 ?