tags:

views:

380

answers:

2

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.

+1  A: 

Ok, assuming I understand your question :) , you want to draw an UILabel centered inside a CGRect/UIView?

There are more than a couple of ways to achieve this, a couple of things you could do are:

UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)];

[aLabel setText:"This is some sample text"];
[aLabel sizeToFit];
/*If it's a CGRect*/
[aLabel setCenter:CGPointMake(CGRectGetMidX(someCGRect),CGRectGetMidY(someCGRect))];

/*If the rect it's an UIView (or something that inherits from that)*/
[aLabel setCenter:[aView center]];

/* add aLabel to UIView as a subView etc. */

Hope this is what you are looking for.

Mr.Gando
The default is default text alignment is UITextAlignmentCenter, but you might want to explicitly set it just to be sure.
Corey Floyd
I'm trying to avoid using a label but want to directly draw to the CGContext
Xetius
+3  A: 

Well, the font property "pointSize" corresponds directly to the height in pixels of a string drawn in that font, 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.

Amagrammer
This is very close to what I eventually went with. Thanks
Xetius
You are welcome. What did you change, if I may ask?
Amagrammer