Search code examples
objective-cxcodecocoanscolornsgradient

NSGradient into NSColor


OK, long story short:

  • I'm using (embedded into the bundle) FontAwesome
  • I'm using it as the font in some custom NSButtons
  • In the NSButton subclass I want to colour them, exactly the way the Xcode tab items are coloured

Colour gradient Xcode

This is how I'm setting the color (as a simple NSColor):

    NSColor *color = [NSColor colorWithCalibratedRed:0.09 green:0.55 blue:0.90 alpha:1.0];
    NSMutableAttributedString *colorTitle =
    [[NSMutableAttributedString alloc] initWithAttributedString:[self attributedTitle]];

    NSRange titleRange = NSMakeRange(0, [colorTitle length]);

    [colorTitle addAttribute:NSForegroundColorAttributeName
                       value:color
                       range:titleRange];

    [self setAttributedTitle:colorTitle];

How can I set it to an NSGradient?


Solution

  • OK, here's the solution, for anyone who may find useful...

    Step 1:

    Create a category on NSColor, based on the great answer by @Omz. In the code below, you'll see it renamed as colorFromGradient:, solely in order to mix well with the usual Cocoa naming conventions...

    Step 2:

    Redraw the title with the gradient color

        NSColor* gS = [NSColor colorWithCalibratedRed:0.07 green:0.47 blue:0.87 alpha:1.0];
        NSColor* gE = [NSColor colorWithCalibratedRed:0.12 green:0.64 blue:0.94 alpha:1.0];
        NSGradient* g = [[NSGradient alloc] initWithStartingColor:gE endingColor:gS];
        NSColor *color = [NSColor colorFromGradient:g];
    
        NSMutableAttributedString *colorTitle =
        [[NSMutableAttributedString alloc] initWithAttributedString:[self attributedTitle]];
    
        NSRange titleRange = NSMakeRange(0, [colorTitle length]);
    
        [colorTitle addAttribute:NSForegroundColorAttributeName
                           value:color
                           range:titleRange];
    
        [self setAttributedTitle:colorTitle];
    

    Step 3:

    Enjoy the result. :-)

    NSGradient to NSColor applied to FontAwesome