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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With