I have a method that draws an NSAttributedString in a rect:
-(void)drawInRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self);
// left column form
CGMutablePathRef leftColumnPath = CGPathCreateMutable();
CGPathAddRect(leftColumnPath, NULL, CGRectMake(rect.origin.x, -rect.origin.y, rect.size.width, rect.size.height));
// left column frame
CGFloat translateAmount = rect.size.height;
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, translateAmount);
CGContextScaleCTM(context, 1.0, -1.0);
CTFrameRef leftFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), leftColumnPath, NULL);
CTFrameDraw(leftFrame, context);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, translateAmount);
CGContextScaleCTM(context, 1.0, -1.0);
CFRelease(leftFrame);
CFRelease(framesetter);
CGPathRelease(leftColumnPath);
}
I put this together a couple months ago with some help from tutorials. It turns out though that this, by default, draws the string left aligned. I'm not too crafty with Core Text, does anyone know how I might be able to draw this with text alignment center?
(Please don't recommend outside label drawing class, I need to do this with Core Text).
Set the CTTextAlignment
of the CTParagraphStyle
to kCTCenterTextAlignment
for the range of the attributed string you want centered.
Then create the CTFramesetter
, then draw.
Example: http://foobarpig.com/iphone/coretext-set-text-font-and-alignment-to-cfattributedstring.html