NSView with gradient background


/ Published in: Objective C
Save to your folder(s)



Copy this code and paste it in your HTML
  1. @interface ColorGradientView : NSView
  2. {
  3. NSColor *startingColor;
  4. NSColor *endingColor;
  5. int angle;
  6. }
  7.  
  8. // Define the variables as properties
  9. @property(nonatomic, retain) NSColor *startingColor;
  10. @property(nonatomic, retain) NSColor *endingColor;
  11. @property(assign) int angle;
  12.  
  13. @end
  14.  
  15. @implementation ColorGradientView
  16.  
  17. // Automatically create accessor methods
  18. @synthesize startingColor;
  19. @synthesize endingColor;
  20. @synthesize angle;
  21.  
  22. - (id)initWithFrame:(NSRect)frame;
  23. {
  24. if (self = [super initWithFrame:frame]) {
  25. [self setStartingColor:[NSColor colorWithCalibratedWhite:1.0 alpha:1.0]];
  26. [self setEndingColor:nil];
  27. [self setAngle:270];
  28. }
  29. return self;
  30. }
  31.  
  32. - (void)drawRect:(NSRect)rect;
  33. {
  34. if (endingColor == nil || [startingColor isEqual:endingColor]) {
  35. // Fill view with a standard background color
  36. [startingColor set];
  37. NSRectFill(rect);
  38. }
  39. else {
  40. // Fill view with a top-down gradient
  41. // from startingColor to endingColor
  42. NSGradient* aGradient = [[[NSGradient alloc]
  43. initWithStartingColor:startingColor
  44. endingColor:endingColor] autorelease];
  45. [aGradient drawInRect:[self bounds] angle:angle];
  46. }
  47. }
  48.  
  49. - (void)setStartingColor:(NSColor *)newColor;
  50. {
  51. [startingColor autorelease];
  52. startingColor = [newColor retain];
  53.  
  54. [self setNeedsDisplay:YES];
  55. }
  56.  
  57. - (void)setEndingColor:(NSColor *)newColor;
  58. {
  59. [endingColor autorelease];
  60. endingColor = [newColor retain];
  61.  
  62. [self setNeedsDisplay:YES];
  63. }
  64.  
  65. - (void)dealloc;
  66. {
  67. [self setStartingColor:nil];
  68. [self setEndingColor:nil];
  69. [super dealloc];
  70. }
  71.  
  72. @end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.