Sunday, March 28, 2010

Cocoa: Draw your Shelf!

Back a bit to play with cocoa, new file-systems need new metaphor for desktop, Shelves? Below you can find a simple draw code, that you can port easily in qt or other library that have a good painter.

The code is really simple, just draw a rectangle and a path to give a perspective effect.
- (void)drawRect:(NSRect)frameRect {
  NSGradient *gradient;
  NSColor *startColor;
  NSColor *endColor;
  NSBezierPath *path;

  [NSGraphicsContext saveGraphicsState];

  CGFloat height = frameRect.size.height - 1.0f;
  CGFloat width = frameRect.size.width - 1.0f;
  CGFloat pcp = 10.0f;
  CGFloat sh = 10.0f;     /* shelf Height */

  path = [NSBezierPath bezierPath];
  [path setLineJoinStyle:NSRoundLineJoinStyle];
  [path moveToPoint:NSMakePoint(0.0f, sh)];
  [path lineToPoint:NSMakePoint(width, sh)];
  [path lineToPoint:NSMakePoint(width - pcp, height)];
  [path lineToPoint:NSMakePoint(pcp, height)];
  [path fill];

  startColor = [NSColor colorWithCalibratedRed:0.85f
                        green:0.66f blue:0.45f alpha:1.0f];
  endColor = [NSColor colorWithCalibratedRed:0.78f
                      green:0.61f blue:0.42f alpha:1.0f];
  gradient = [[NSGradient alloc] initWithStartingColor:startColor
                          endingColor:endColor];
  [gradient drawInBezierPath:path angle:90.0f];
  [gradient release];

  path = [NSBezierPath bezierPathWithRect:NSMakeRect(0.0f, 0.0f, width, sh)];
  startColor = [NSColor colorWithCalibratedRed:0.29f
                        green:0.16f blue:0.04f alpha:1.0f];
  endColor = [NSColor colorWithCalibratedRed:0.48f
                      green:0.30f blue:0.16f alpha:1.0f];
  gradient = [[NSGradient alloc] initWithStartingColor:startColor
                                  endingColor:endColor];
  [gradient drawInBezierPath:path angle:90.0f];
  [gradient release];

  [NSGraphicsContext restoreGraphicsState];
}