设置CALayer的渐变背景(Set CALayer Gradient Background)

2019-10-23 09:37发布

我想添加到一个的CALayer我创建了一个梯度。 我可以设置用以下的CALayer的背景色:

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

我环顾四周,但没有成功(令人惊讶的我认为这将已经回答了很多次)。

我与一个梯度:

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

但不能将其添加到我的CALayer或添加的角度。

Answer 1:

你并不需要一个渐变添加到CALayer的,因为你可以用一个CAGradientLayer代替。



Answer 2:

    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];


Answer 3:

斯威夫特4版本的这个答案

    let gradient = CAGradientLayer()
    gradient.colors = [NSColor.hlpMarineBlue, NSColor.hlpDarkishBlue, NSColor.hlpOceanBlue]
    gradient.frame = self.backgroundView.bounds;
    self.colorView.layer = gradient
    self.colorView.wantsLayer = true


文章来源: Set CALayer Gradient Background