Search code examples
cocoacore-graphicsnsimage

NSGradient created with initWithColorsAndLocations: does not draw


I created a gradient like this:

NSGradient *g = [[NSGradient alloc] initWithColorsAndLocations:
                 [NSColor colorWithWhite:1 alpha:1], 0,
                 [NSColor colorWithWhite:0 alpha:0], 1, nil];

But when I draw it into an image using drawInRect:angle:, I get a plain white image instead of a gradient. What's wrong?


Solution

  • Since -initWithColorsAndLocations: is a variadic function, the compiler doesn't know what types the arguments need to be (beyond the first argument). The callee requires that the "locations" be CGFloat values, but when 1 or 0 is passed, it's passed as an int, so it gets interpreted as a very small floating-point value.

    The solution is to pass (CGFloat)0.0 and (CGFloat)1.0 for the locations instead of 0 and 1.