xcode 设置CALayer渐变背景

insrf1ej  于 2022-12-24  发布在  其他
关注(0)|答案(4)|浏览(184)

我正在尝试为我创建的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或添加Angular 。

kxeu7u2r

kxeu7u2r1#

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

nbewdwxp2#

您不需要将渐变添加到CALayer,因为您可以使用CAGradientLayer。

mwngjboj

mwngjboj3#

this answer的Swift 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
62o28rlo

62o28rlo4#

//用途:

guard let firstColot: NSColor = NSColor(hexString: HexColorCode.code.leftMenuFirstColor.rawValue) else {return}
guard let secondColor: NSColor = NSColor(hexString: HexColorCode.code.leftMenuSecondColor.rawValue) else {return}
    
leftMenuBgView.gradient(fillView: leftMenuBgView,
                            withGradientFromColors: [firstColot, secondColor])


extension NSView {

func gradient(fillView view: NSView, withGradientFromColors colors: Array<NSColor>) {
    self.wantsLayer = true
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = view.bounds
    let color1 = colors[0].cgColor
    let color2 = colors[1].cgColor
    gradientLayer.colors = [color1, color2]
    gradientLayer.locations = [0.0, 1.0]
    self.layer?.insertSublayer(gradientLayer, at: 0)
  }
}

相关问题