Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSString drawInRect to center text?

How can I draw a NSString centered within a NSRect?

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?

like image 277
Steve Folly Avatar asked Jan 25 '09 10:01

Steve Folly


3 Answers

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

NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentCenter;
NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName];
[myString drawInRect:someRect withAttributes:attr];
like image 197
Martin Pilkington Avatar answered Nov 06 '22 09:11

Martin Pilkington


This works for me for horizontal alignment

[textX drawInRect:theRect 
         withFont:font 
    lineBreakMode:UILineBreakModeClip 
        alignment:UITextAlignmentCenter];
like image 34
Nikolay Klimchuk Avatar answered Nov 06 '22 09:11

Nikolay Klimchuk


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.

like image 19
matthewwithanm Avatar answered Nov 06 '22 08:11

matthewwithanm