Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

swift3 - Swift - UI Button Shadow Gradient

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

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

Now I am trying to recreate the glow effect behind the button. I was thinking creating a subview behind it and using a gaussian blur filter to draw it. Now I am stuck in how to implement this, and haven't found a good solution. The normal CALayer shadow doesn't work with gradients, and I am lost. Any help is appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...