Skip to content

Instantly share code, notes, and snippets.

@fiftytwo
Last active August 29, 2015 14:23
Show Gist options
  • Save fiftytwo/4619dd5a0f514dd9128b to your computer and use it in GitHub Desktop.
Save fiftytwo/4619dd5a0f514dd9128b to your computer and use it in GitHub Desktop.
// Needed to work with attributed strings
#import <CoreText/CoreText.h>
// Somewhere in drawing code, that renders string:
NSMutableParagraphStyle *paragraphStyle = [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease];
paragraphStyle.alignment = alignments[hAlignment];
paragraphStyle.lineBreakMode = linebreaks[lineBreakMode];
NSDictionary *attributes = @{
NSFontAttributeName: uiFont,
NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName: [UIColor whiteColor]
};
NSAttributedString *attrString = [[[NSAttributedString alloc] initWithString:string attributes:attributes] autorelease];
CGRect drawArea;
if (vAlignment == kCCVerticalTextAlignmentTop)
drawArea = CGRectMake(0, 0, dimensions.width, dimensions.height);
else
{
CGSize drawSize = [attrString boundingRectWithSize:dimensions
options:NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
context:nil].size;
if (vAlignment == kCCVerticalTextAlignmentBottom)
drawArea = CGRectMake(0, dimensions.height - drawSize.height, dimensions.width, drawSize.height);
else // kCCVerticalTextAlignmentCenter
drawArea = CGRectMake(0, (dimensions.height - drawSize.height) / 2, dimensions.width, drawSize.height);
}
[attrString drawInRect:drawArea];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment