gpt4 book ai didi

swift - 如何制作带有渐变的 UIButton 背景图像(Swift)

转载 作者:搜寻专家 更新时间:2023-10-31 22:39:15 25 4
gpt4 key购买 nike

enter image description here

请大家帮助我如何制作这样的 UIButton,我之前已经搜索过解决方案,但找不到任何人。谢谢!

最佳答案

声明新的按钮子类:

class GradientButton : UIButton {

var leftColor = UIColor.red
var rightColor = UIColor.green
var customImage : UIImage? {
didSet {
updateImageView()
}
}
let gradientLayer = CAGradientLayer()
let customImageView = UIImageView()

override var frame: CGRect {
didSet {
gradientLayer.frame = bounds
layer.layoutIfNeeded()
}
}

convenience init(leftColor: UIColor, rightColor: UIColor, image: UIImage) {
self.init()

self.leftColor = leftColor
self.rightColor = rightColor
customImage = image
updateImageView()
}

override init(frame: CGRect) {
super.init(frame: frame)

defaultInitializer()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

defaultInitializer()
}

func defaultInitializer() {

gradientLayer.frame = bounds
gradientLayer.colors = [leftColor.cgColor, rightColor.cgColor]
gradientLayer.startPoint = CGPoint.init(x: 0, y: 0.5)
gradientLayer.endPoint = CGPoint.init(x: 1, y: 0.5)
layer.insertSublayer(gradientLayer, at: 0)
layer.layoutIfNeeded()

addSubview(customImageView)
customImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}

func updateImageView() {
customImageView.image = customImage
customImageView.alpha = 0.2
layoutSubviews()
}
}

初始化如下:

    let rect = CGRect(x: 20, y: 20, width: 200, height: 100)
let button = GradientButton(leftColor: UIColor.red, rightColor: UIColor.cyan, image: UIImage(named: "1")!)
button.frame = rect
self.view.addSubview(button)

甚至使用 Storyboard。

其他设置,如文本颜色、字体等,您可以在 UIButton 声明中找到。编码愉快!

关于swift - 如何制作带有渐变的 UIButton 背景图像(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51550351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com