Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone - How to draw text in the middle of a rect

Tags:

Is there a method to draw text in the middle of a rectangle. I can find various alignments, but nothing I have tried can vertically centre the text in a rect.

Is there a simple method to do this, or is there some way to centre a rectangle and then draw in that?

I'm drawing direct to the CGContext, trying to use NSString::drawWithRect or something similar, as I dont really want to have to add a Label just to render some basic text.

like image 754
Xetius Avatar asked Aug 19 '09 21:08

Xetius


Video Answer


1 Answers

Well, the font property pointSize corresponds directly to the height in pixels of a NSString drawn in that UIFont, so your formula would be something like this:

- (void) drawString: (NSString*) s             withFont: (UIFont*) font               inRect: (CGRect) contextRect {      CGFloat fontHeight = font.pointSize;     CGFloat yOffset = (contextRect.size.height - fontHeight) / 2.0;      CGRect textRect = CGRectMake(0, yOffset, contextRect.size.width, fontHeight);      [s drawInRect: textRect           withFont: font      lineBreakMode: UILineBreakModeClip          alignment: UITextAlignmentCenter]; } 

UITextAlignmentCenter handles the horizontal centering, so we use the full width of the contextRect. The lineBreakMode can be whatever you like.

like image 70
Amagrammer Avatar answered Sep 19 '22 18:09

Amagrammer