Skip to content

Instantly share code, notes, and snippets.

@oliverfoggin
Last active March 9, 2016 06:53
Show Gist options
  • Save oliverfoggin/8822319 to your computer and use it in GitHub Desktop.
Save oliverfoggin/8822319 to your computer and use it in GitHub Desktop.
How to centre text using drawInRect...
//Create the rect you would like your text to be inside of...
CGRect maxTextRect = CGRectMake(0, 0, 200, 60);
//Create the attributed string
NSAttributedString *theString = //... do all the setup.
//Find the rect that the string will draw into **inside the maxTextRect**
CGRect actualRect = [theString boundingRectWithSize:maxTextRect.size options:NSStringDrawingUsesLineFragmentOrigin context:nil];
//Offset the actual rect inside the maxTextRect
// this will center vertically and horizontally
CGRect drawRect = CGRectMake(CGRectGetMinX(maxTextRect) + ((CGRectGetWidth(maxTextRect) - CGRectGetWidth(actualRect)) * 0.5)
, CGRectGetMinY(maxTextRect) + ((CGRectGetHeight(maxTextRect) - CGRectGetHeight(actualRect)) * 0.5)
, CGRectGetWidth(actualRect)
, CGRectGetHeight(actualRect));
//Now draw in that new rect...
[theString drawWithRect:drawRect
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment