Posts tagged ‘Mac OS X 10.5’

NSView with gradient background

In Mac OS X 10.5 a new class NSGradient is introduced, that makes it really easy to work with gradients (as you might have guessed from the name). The sample code below shows a basic yet functional implementation of an NSView subclass that has either an colored or gradient background.

ColorGradientView.h

@interface ColorGradientView : NSView
{
  NSColor *startingColor;
  NSColor *endingColor;
  int angle;
}

// Define the variables as properties
@property(nonatomic, retain) NSColor *startingColor;
@property(nonatomic, retain) NSColor *endingColor;
@property(assign) int angle;

@end

ColorGradientView.m

#import "GradientView.h"
@implementation ColorGradientView

// Automatically create accessor methods
@synthesize startingColor;
@synthesize endingColor;
@synthesize angle;

- (id)initWithFrame:(NSRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    // Initialization code here.
    [self setStartingColor:[NSColor colorWithCalibratedWhite:1.0 alpha:1.0]];
    [self setEndingColor:nil];
    [self setAngle:270];
  }
  return self;
}

- (void)drawRect:(NSRect)rect {
  if (endingColor == nil || [startingColor isEqual:endingColor]) {
    // Fill view with a standard background color
    [startingColor set];
    NSRectFill(rect);
  }
  else {
    // Fill view with a top-down gradient
    // from startingColor to endingColor
    NSGradient* aGradient = [[NSGradient alloc]
        initWithStartingColor:startingColor
        endingColor:endingColor];
    [aGradient drawInRect:[self bounds] angle:angle];
  }
}

@end

Note that the code is based on the new garbage collection mechanism available in Objective-C 2.0, so there are no retain or release calls.

In the following picture you see a gradient effect from top to bottom to give a subtle 3d appearance:

To achieve this, add a NSView in Interface Builder and define its class as ColorGradientView. In your controller, add a ColorGradientView outlet (e.g. myGradientView) and in Interface Builder attach the view to the outlet. Add the following 3 lines to the - (void)awakeFromNib method in the controller:


[myGradientView setStartingColor:
    [NSColor colorWithCalibratedWhite:0.85 alpha:1.0]];
[myGradientView setEndingColor:
    [NSColor colorWithCalibratedWhite:0.7 alpha:1.0]];
[myGradientView setAngle:270];

In upcoming post I will go into details of how to create the Safari like buttons that you see in the screen shot.