如何在包含系统图像的背景按钮中放置渐变?
Posted
技术标签:
【中文标题】如何在包含系统图像的背景按钮中放置渐变?【英文标题】:How to put a gradient in a background button witch contains a system image? 【发布时间】:2020-12-11 04:36:28 【问题描述】:我有一个带有系统图像的按钮:
@IBOutlet weak var ampouleButton: UIButton!
在 viewdid 加载中,我放了这个:
let ampouleButtonConfig = UIImage.SymbolConfiguration(
pointSize: 30,
weight: .regular,
scale: .large)
let ampouleButtonImage = UIImage(
systemName: "lightbulb",
withConfiguration: ampouleButtonConfig)
ampouleButton.backgroundColor = Theme.gold03 // i need to put here a gradient
ampouleButton.setImage(ampouleButtonImage, for: .normal)
ampouleButton.tintColor = Theme.blanc
ampouleButton.layer.cornerRadius = ampouleButton.frame.height / 2
ampouleButton.layer.shadowOpacity = 0.4
ampouleButton.layer.shadowRadius = 3
ampouleButton.layer.shadowOffset =
CGSize(width: 0, height: 5)
ampouleButton.alpha = 1
我需要放一个渐变,而不是背景色。
我对此进行了测试,但没有成功:
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.ampouleButton.bounds
gradientLayer.colors = [UIColor.yellow.cgColor, UIColor.white.cgColor]
ampouleButton.layer.insertSublayer(gradientLayer, at: 0)
【问题讨论】:
***.com/a/62093932/2303865 @LeoDabus 我放置了 UIButton 扩展,并使用我的代码将其添加到视图控制器中: ampouleButton.applyGradient(colors: [Theme.bleu!.cgColor, Theme.softBlue!.cgColor], radius: 1, startGradient: CGPoint(x: 0, y: 0.5), endGradient: CGPoint(x: 1, y: 0)) 但是按钮看起来像正方形而不是圆形,并且灯泡消失了 @LeoDabus 灯泡不见了,我需要它。对于正方形,我将 self.ampouleButton.frame.height / 2 放在半径中 @matt setBackgroundImage 使灯泡系统名称图像消失 或者您可以在应用渐变后手动添加此代码。 if let imgView = ampouleButton.imageView ampouleButton.bringSubviewToFront(imgView) 【参考方案1】:实际上,按钮图像位于图层后面。试试这个:
extension UIButton
func applyGradient(colors: [CGColor], radius: CGFloat = 0, startGradient: CGPoint = .init(x: 0.5, y: 0), endGradient: CGPoint = .init(x: 0.5, y: 1))
// check first if there is already a gradient layer to avoid adding more than one
let gradientLayer = CAGradientLayer()
gradientLayer.cornerRadius = radius
gradientLayer.colors = colors
gradientLayer.startPoint = startGradient
gradientLayer.endPoint = endGradient
gradientLayer.frame = bounds
layer.insertSublayer(gradientLayer, at: 0)
并在 viewDidLoad 中放:
ampouleButton.applyGradient(colors: [Theme.bleu!.cgColor, Theme.softBlue!.cgColor], radius: self.ampouleButton.frame.height / 2, startGradient: CGPoint(x: 0, y: 0.5), endGradient: CGPoint(x: 1, y: 0))
if let imgView = ampouleButton.imageView ampouleButton.bringSubviewToFront(imgView)
从这里找到 applyGradient 函数:https://***.com/a/62093932/2303865
【讨论】:
以上是关于如何在包含系统图像的背景按钮中放置渐变?的主要内容,如果未能解决你的问题,请参考以下文章