Archive for June, 2006

Of Colour Wells and Alpha

Tuesday, June 20th, 2006

Many applications require a mix of colour pickers: some that support transparency (alpha) values, and some that don’t. For some reason Apple decided not to make this totally straight forward to implement, even if it is fairly simple to do when you know how.

To support this you need to create two subclasses of NSColorWell, teach Interface Builder about those subclasses and set colour wells in the interface to use the right class.

I created these classes for use in ControlTower, but I would guess they’ll be of use to other Mac OS X developers, so here they are. Feel free to use or abuse them as you see fit.

NSColorWellWithAlpha.h

//
//  NSColorWellWithAlpha.h
//  ControlTower
//
//  Created by Andrew Wellington on 30/04/06.
//  Copyright 2006 Andrew Wellington. All rights reserved.
//

#import 


@interface NSColorWellWithAlpha : NSColorWell {

}

@end

NSColorWellWithAlpha.m

//
//  NSColorWellWithAlpha.m
//  ControlTower
//
//  Created by Andrew Wellington on 30/04/06.
//  Copyright 2006 Andrew Wellington. All rights reserved.
//

#import "NSColorWellWithAlpha.h"


@implementation NSColorWellWithAlpha
- (void)activate:(BOOL)exclusive
{
    [[NSColorPanel sharedColorPanel] setShowsAlpha:YES];
    [super activate: exclusive];
}
@end

NSColorWellWithoutAlpha.h

//
//  NSColorWellWithoutAlpha.h
//  ControlTower
//
//  Created by Andrew Wellington on 30/04/06.
//  Copyright 2006 Andrew Wellington. All rights reserved.
//

#import 


@interface NSColorWellWithoutAlpha : NSColorWell {

}

@end

NSColorWellWithoutAlpha.m

//
//  NSColorWellWithoutAlpha.m
//  ControlTower
//
//  Created by Andrew Wellington on 30/04/06.
//  Copyright 2006 Andrew Wellington. All rights reserved.
//

#import "NSColorWellWithoutAlpha.h"

@implementation NSColorWellWithoutAlpha
- (void)activate:(BOOL)exclusive
{
    [super activate: exclusive];
    [[NSColorPanel sharedColorPanel] setShowsAlpha:NO];
}
@end

Importing into Interface Builder

Simply drag the header files to the main window for the nib (the window that contains the objects in the nib). Set the Custom Class in the Inspector for a NSColorWell to use the correct class based on whether it needs alpha support or not.

That’s it. Easy isn’t it?