Swift - UI Button Shadow Gradient

后端 未结 1 1270
-上瘾入骨i
-上瘾入骨i 2021-02-04 19:53

I am trying to recreate a button like this in Swift:

I have been able to create the gradient inside of the button accurately from Sketch using the help from here: Answe

1条回答
  •  花落未央
    2021-02-04 20:30

    You can do it like this

    Init your gradient layer

    let gradientLayer = CAGradientLayer.init()
    
    gradientLayer.colors = [UIColor.red.cgColor,
                            UIColor.yellow.cgColor,
                            UIColor.green.cgColor,
                            UIColor.blue.cgColor]
    
    gradientLayer.transform = CATransform3DMakeRotation(CGFloat.pi / 2, 0, 0, 1)
    

    Set preferable size for example 40 from button's frame

    gradientLayer.frame = CGRect.init(
    x: button.frame.minX - 40,
    y: button.frame.minY - 40, 
    width: button.frame.width + 80, 
    height: button.frame.height + 80)
    gradientLayer.masksToBounds = true
    

    Init shadow layer

    let shadowLayer = CALayer.init()
    shadowLayer.frame = gradientLayer.bounds
    shadowLayer.shadowColor = UIColor.black.cgColor
    shadowLayer.shadowOpacity = 0.08
    shadowLayer.shadowRadius = 20
    shadowLayer.shadowPath = CGPath.init(rect: shadowLayer.bounds, transform: nil)
    

    Set the shadow layer as a mask for gradient layer

    gradientLayer.mask = shadowLayer
    

    Insert gradient layer in button's superView below button's layer

    backgroungView.layer.insertSublayer(gradientLayer, below: button.layer)
    

    0 讨论(0)
提交回复
热议问题