I Have a custom button:
My Button http://cld.ly/29ubq
And I need the text to be centered, here’s my code:
NSMutableParagraphStyle *style =
[[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];
[style setAlignment:NSLeftTextAlignment];
att = [[NSDictionary alloc] initWithObjectsAndKeys:
style, NSParagraphStyleAttributeName,
[NSColor blackColor],
NSForegroundColorAttributeName, nil];
[style release];
// other Drawing code here
[[self title] drawInRect:[self bounds] withAttributes:att];
How do I center the text in the center of my button (not center of the bounds)?
You want to get the size of the title first using
NSString -sizeWithAttributes:. Then you can use that size to adjust the drawing of title within your bounds.There is a trick to this, since you will almost always wind up dividing by two at some point in this process. When you do that, you may wind up with a half-pixel result, which Cocoa will happily use. However, it will cause your text to be blurry. You almost always want to call
floor()on your coordinates before drawing on them to get yourself back onto integral pixels.Edit: A basic example of centering (this should compile correctly, I haven’t compiled it and my recent work has been over on iPhone which is upside-down):
Anyway, something along those lines. You may want to offset a bit because of how your button draws, but this is the basic idea.