Convert NSGradient to NSColor

1.1k Views Asked by At

Is it possible to convert an NSGradient to an NSColor

- (void) viewWillDraw {
    NSGradient *grad = [[NSGradient alloc] initWithStartingColor:[NSColor lightGrayColor]    endingColor:[NSColor darkGrayColor]];
    [super setBackgroundColor:*gradient*;
}

This is my method, I want to be able to pass the NSGradient in as an NSColor, which obviously i cant, is there any way to convert it to one?

2

There are 2 best solutions below

2
On

NSGradient is not Convertible to NSColor.

The NSGradient class provides support for drawing gradient fill colors, also known as shadings in Quartz. This class provides convenience methods for drawing radial or linear (axial) gradients for rectangles and NSBezierPath objects.

As you want to set the viewBackground to to an effect (Gradient effect) you need to do as:

[grad drawInRect:<the rect of your view> angle:270]; //angle is upto your requirement,
2
On

On 10.8, you can create, in the following order:

  1. A block that draws the gradient however you like.
  2. An image that is backed by the block.
  3. A color that repeats the image as a pattern.

In this way, you can create a color that looks like anything, including a gradient.

That said, this may not work correctly with window resizing if you try to have the gradient adapt to the size of the background (by using the rect passed to the block) and the background is of a text view in a scroll view. (When I tried it awhile back, the pattern didn't redraw the block; it simply tiled, which looked weird in at least one dimension.) If either your gradient or your window is fixed in size, then you will not have that problem.