Last active
March 9, 2016 06:53
-
-
Save oliverfoggin/8822319 to your computer and use it in GitHub Desktop.
How to centre text using drawInRect...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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