Set CALayer Gradient Background

2019-08-14 17:48发布

I am trying to add a gradient to a CALayer I have created. I can set the background colour of the CALayer with the following:

self.colorLayer = [CALayer layer];
[self.colorLayer setBackgroundColor:color.CGColor]; 
[self.colorView setWantsLayer:YES]; 
[self.colorView setLayer:self.colorLayer];

I've looked around with no success (surprisingly I thought this would have been answered many times).

I have made a gradient with:

NSGradient *gradient = 
    [[NSGradient alloc] initWithStartingColor:[NSColor orangeColor] 
        endingColor:[NSColor lightGrayColor]];

But can't add it to my CALayer or add an angle.

3条回答
趁早两清
2楼-- · 2019-08-14 18:24

Swift 4 version of this answer

    let gradient = CAGradientLayer()
    gradient.colors = [NSColor.hlpMarineBlue, NSColor.hlpDarkishBlue, NSColor.hlpOceanBlue]
    gradient.frame = self.backgroundView.bounds;
    self.colorView.layer = gradient
    self.colorView.wantsLayer = true
查看更多
Anthone
3楼-- · 2019-08-14 18:28

You don't need to add a gradient to a CALayer, because you can use a CAGradientLayer instead.

查看更多
倾城 Initia
4楼-- · 2019-08-14 18:41
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.colors = [NSArray arrayWithObjects:(id)[[NSColor whiteColor] CGColor], (id)[[NSColor greenColor] CGColor], nil];
    gradient.frame = self.colorView.bounds;
    [self.colorView setLayer:gradient];
    [self.colorView setWantsLayer:YES];
查看更多
登录 后发表回答