Set CALayer Gradient Background

对着背影说爱祢 提交于 2019-12-24 17:06:40

问题


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.


回答1:


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




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



回答3:


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


来源:https://stackoverflow.com/questions/30876811/set-calayer-gradient-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!