Swift-UI按钮阴影渐变 [英] Swift - UI Button Shadow Gradient
问题描述
我正在尝试在Swift中重新创建这样的按钮:
I am trying to recreate a button like this in Swift:
我已经能够使用此处的帮助从Sketch中准确地在按钮内部创建渐变: 已回答的问题
I have been able to create the gradient inside of the button accurately from Sketch using the help from here: Answered Question
现在,我正在尝试在按钮后面重新创建发光效果.我当时正在考虑在其后面创建一个子视图,并使用高斯模糊滤镜对其进行绘制.现在,我被困在如何实现这一点上,还没有找到一个好的解决方案.正常的CALayer阴影不适用于渐变色,我迷路了.感谢您的帮助
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
推荐答案
您可以这样做
初始化您的渐变层
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)
设置按钮边框的首选大小,例如40
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
初始化阴影层
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
在按钮的superView中将渐变图层插入按钮的图层下方
Insert gradient layer in button's superView below button's layer
backgroungView.layer.insertSublayer(gradientLayer, below: button.layer)
这篇关于Swift-UI按钮阴影渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!