What is the best way to create an NSButton with a custom background image, that is able to have variable width, without making the corner bezel look stretched? I know there are convenience methods to do this with UIButton: http://jainmarket.blogspot.com/2009/04/create-uibuttonbutton-with-images.html but I haven't seen anything similar in NSButton.
+1
A:
NSButton
doesn't have the same convenience methods for background images as UIButton
(which is odd and here's to hoping Apple bridges that gap). You'll need to create a custom button my subclassing NSView
and handling the variable width and corners yourself. I don't think it will be easy, but I don't think it would be terribly difficult either.
Philip Regan
2010-09-18 00:10:40
Shame right? :) Not like the convenience method in UIButton is really that convenient.
BadPirate
2010-09-20 22:18:41
A:
I needed to have a custom button background, here's how I did it. I made an NSButton subclass and overrode drawrect method:
- (void)drawRect:(NSRect)dirtyRect
{
// My buttons don't have a variable height, so I make sure that the height is fixed
if (self.frame.size.height != 22) {
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width,
22.0f);
}
//
switch (self.state) {
// Onstate graphics
case NSOnState:
NSDrawThreePartImage(self.bounds,
[NSImage imageNamed:@"btnmain_lb_h.png"], [NSImage imageNamed:@"btnmain_bg_h.png"], [NSImage imageNamed:@"btnmain_rb_h.png"],
NO, NSCompositeSourceAtop, 1.0, NO);
// Offstate graphics
default:
case NSOffState:
NSDrawThreePartImage(self.bounds,
[NSImage imageNamed:@"btnmain_lb.png"], [NSImage imageNamed:@"btnmain_bg.png"], [NSImage imageNamed:@"btnmain_rb.png"],
NO, NSCompositeSourceAtop, 1.0, NO);
break;
}
[super drawRect:dirtyRect];
}
Then I could put the buttons using Interface Builder, and to get the custom graphics I just have to change the class to my new subclass.
BadPirate
2010-09-20 22:18:04