October 2007

Constructing an NSColor from Color panel values

I often find myself constructing an NSColor object based on having sampled a color using the standard Color panel. The issue, of course, is that you need to divide the values in the picker by 255 to get the respective red/green/blue components for an RGB NSColor, as those constructors take values in the 0-1 range.

Here’s a trivial category on NSColor to allow you to use the values straight out of the Color panel.

Header:

#import <Cocoa/Cocoa.h>

@interface NSColor (PickerValues)

+ (NSColor *)colorWithCalibratedPickerRed:(float)red green:(float)green
                                     blue:(float)blue alpha:(float)alpha;

@end

Implementation:

#import "NSColor+PickerValues.h"

@implementation NSColor (PickerValues)

+ (NSColor *)colorWithCalibratedPickerRed:(float)red green:(float)green
                                     blue:(float)blue alpha:(float)alpha
{
    float maxVal = 255.0;
    return [NSColor colorWithCalibratedRed:(red / maxVal)
                                     green:(green / maxVal)
                                      blue:(blue / maxVal)
                                     alpha:alpha];
}

@end

Cocoa

Comments (0)

Permalink

Setting the text color of an NSButton

In this era of white-on-black (HUD) interfaces, we often want to change the text-color of NSButtons (including checkboxes and such). NSTextFieldCell has a -setTextColor: method, but NSButtonCell doesn’t. You can use -setAttributedTitle: to achieve the desired result, but that’s a bit of a hassle.

Here’s a simple little category on NSButton which adds -textColor and -setTextColor: methods to the class.

Header:

#import <Cocoa/Cocoa.h>

@interface NSButton (TextColor)

- (NSColor *)textColor;
- (void)setTextColor:(NSColor *)textColor;

@end

Implementation:

#import "NSButton+TextColor.h"

@implementation NSButton (TextColor)

- (NSColor *)textColor
{
    NSAttributedString *attrTitle = [self attributedTitle];
    int len = [attrTitle length];
    NSRange range = NSMakeRange(0, MIN(len, 1)); // take color from first char
    NSDictionary *attrs = [attrTitle fontAttributesInRange:range];
    NSColor *textColor = [NSColor controlTextColor];
    if (attrs) {
        textColor = [attrs objectForKey:NSForegroundColorAttributeName];
    }
    return textColor;
}

- (void)setTextColor:(NSColor *)textColor
{
    NSMutableAttributedString *attrTitle = [[NSMutableAttributedString alloc]
                                 initWithAttributedString:[self attributedTitle]];
    int len = [attrTitle length];
    NSRange range = NSMakeRange(0, len);
    [attrTitle addAttribute:NSForegroundColorAttributeName
                      value:textColor
                      range:range];
    [attrTitle fixAttributesInRange:range];
    [self setAttributedTitle:attrTitle];
    [attrTitle release];
}

@end

Cocoa

Comments (1)

Permalink