Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.