Saturday, November 15, 2008

Cocoa: Drawing Images, Texts and Shadows

Today I'm playing a bit with Quartz and Cocoa Drawing system (that is based on Quartz).

I've made a simple example that you can see below where I've used custom NSView that draws an Image and a Bezier Path with some text inside, and around the Bezier Path there's a Shadow.
...And this is the drawRect method source code of the custom NSView.

- (void)drawRect:(NSRect)frameRect {
  [NSGraphicsContext saveGraphicsState];

  [[NSColor colorWithCalibratedRed:0.64 green:0.66 blue:0.71 alpha:1.0] set];
  NSRectFill(frameRect);

  /* Draw Shadow */
  NSShadow *shadow = [[NSShadow alloc] init];
  [shadow setShadowColor:[[NSColor blackColor] colorWithAlphaComponent:0.5]];
  [shadow setShadowOffset:NSMakeSize(4.0, -4.0)];
  [shadow setShadowBlurRadius:3.0];
  [shadow set];

  /* Draw Control */
  NSRect myRect = NSMakeRect(80, 50, frameRect.size.width - 120, 60);
  NSBezierPath *path = [NSBezierPath bezierPath];
  [path setLineJoinStyle:NSRoundLineJoinStyle];
  [path appendBezierPathWithRoundedRect:myRect xRadius:8.0 yRadius:8.0];    

  [path moveToPoint:NSMakePoint(80, 75)];
  [path lineToPoint:NSMakePoint(65, 85)];
  [path lineToPoint:NSMakePoint(80, 95)];

  NSColor *startingColor = [NSColor colorWithCalibratedRed:0.90
  green:0.92 blue:0.85 alpha:1.0];
  NSColor *endingColor = [NSColor colorWithCalibratedRed:0.81
                               green:0.83 blue:0.76 alpha:1.0];
  NSGradient *gradient = [[[NSGradient alloc] initWithStartingColor:startingColor
                              endingColor:endingColor] autorelease];
  [path fill];
  [gradient drawInBezierPath:path angle:90];

  [NSGraphicsContext restoreGraphicsState];

  [shadow release];

  NSImage *image = [NSImage imageNamed:NSImageNameUser];
  [image drawInRect:NSMakeRect(15, 50, 50, 50) fromRect:NSZeroRect
                operation:NSCompositeSourceOver fraction:1.0];

  NSString *string = [NSString stringWithString:@"Text\nMore Text"];
  [string drawInRect:NSMakeRect(90, 60, frameRect.size.width - 140, 45)
               withAttributes:nil];
}

No comments:

Post a Comment