问题
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