iosgradientcagradientlayerasyncdisplaykit

How to add gradient to ASDisplayNode or ASButtonNode


I am looking to add a gradient background to an ASDisplayNode/ASButtonNode. I have tried creating a gradient layer and adding it as a sublayer like this -

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = button.frame;
gradient.colors = @[[UIColor redColor], [UIColor blueColor]];
[button.view.layer insertSublayer:gradient atIndex:0];

where button is of type ASButtonNode, but this just gives a white background to the button. I haven't been able to find much documentation for achieving this either.

How can I go about adding a background given an array of UIColor and a CGFloat angle?

Thanks


Solution

  • Swift 3.

    extension UIView {
    
           func gradient(color1: UIColor, color2: UIColor) -> CAGradientLayer {
                 let gradient: CAGradientLayer = CAGradientLayer()
                 gradient.colors = [color1.cgColor, color2.cgColor]
                 gradient.locations = [0.0 , 1.0]
                 gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
                 gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
                 gradient.frame = CGRect(x: 0.0, y: 0.0, width: frame.size.width, height: frame.size.height)
                 return gradient
              } 
        }
    

    Example:

    let gradient = self.cardGradientNode.view.gradient(
        color1: gradient.start, 
        color2: gradient.end
    )
    self.cardGradientNode.view.layer.insertSublayer(gradient, at: 0)
    

    Result: enter image description here