本文介绍了Swift - UI 按钮阴影渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 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 按钮阴影渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:54