views:

3824

answers:

5

How can I draw a string centred within a rect?

I've started off with: (an extract from the drawRect method of my custom view)

NSString* theString = ...
[theString drawInRect:theRect withAttributes:0];
[theString release];

Now I'm assuming I need to set up some attributes. I've had a look through Apple's Cocoa documentation, but it's a bit overwhelming and can't find anything for how to add paragraph styles to the attributes.

Also, I can only find horizontal alignment, what about vertical alignment?

Thanks.

+1  A: 

Well, drawInRect is only good for basic text drawing (in other words, the system decides where to position your text) - often the only way to draw text positioned where you want is to simply calculate what point you want it at and use NSString's drawAtPoint:withAttributes:.

Also, NSString's sizeWithAttributes is hugely useful in any positioning math you end up having to do for drawAtPoint.

Good luck!

Joel Levin
+6  A: 

Vertical alignment you'll have to do yourself ((height of view + height of string)/2). Horizontal alignment you can do with:

NSMutableParagraphStyle *style = [NSMutableParagraphStyle defaultParagraphStyle];
[style setAlignment:NSCenterTextAlignment];
NSDictionary *attr = [NSDictionary dictionaryWithObject:style andKey:@"NSParagraphStyleAttributeName"];
[myString drawInRect:someRect withAttributes:attr];
Martin Pilkington
A: 

[NSMutableParagraphStyle defaultParagraphStyle] won't work use:

[NSMutableParagraphStyle new]

also, it appears horizontal alignment only works for drawInRect, not drawAtPoint (ask me how I know :-)

David H
Don't forget to release that object you created using +new.
Peter Hosey
+5  A: 

Martins answer is pretty close, but it has a few small errors. Try this:

NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
[style setAlignment:NSCenterTextAlignment];
NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName];
[myString drawInRect:someRect withAttributes:attr];
[style release];

You'll have to create a new NSMutableParagraphStyle (instead of using the default paragraph style as Martin suggested) because [NSMutableParagraphStyle defaultParagraphStyle] returns an NSParagraphStyle, which doesn't have the setAlignment method. Also, you don't need the string @"NSParagraphStyleAttributeName"—just NSParagraphStyleAttributeName.

matthew
Checkout Nikolays answer - it's much simpler.
Stiefel
+3  A: 

This works for me for horizontal alignment

[textX drawInRect:theRect withFont:font lineBreakMode:UILineBreakModeClip alignment:UITextAlignmentCenter];
Nikolay Klimchuk