Drawing text in a NSButton subclass - positioning
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,
开发者_JAVA技巧 [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):
NSRect rect;
rect.size = [[self title] sizeWithAttributes:att];
rect.origin.x = floor( NSMidX([self bounds]) - rect.size.width / 2 );
rect.origin.y = floor( NSMidY([self bounds]) - rect.size.height / 2 );
[[self title] drawInRect:rect withAttributes:att];
Anyway, something along those lines. You may want to offset a bit because of how your button draws, but this is the basic idea.
You could be interested in Setting a Button’s Image, which also explain how to position the title relative to the button’s image.
精彩评论