根据背景图片更改UIButton的色调颜色

时间:2020-04-21 09:01:38

标签: ios swift uibutton uiimageview

我有一个带有白色色调的关闭按钮的UIImageView,但是如果背景图像为白色,则UIbutton不可见。我需要根据背景图像的颜色以编程方式更改UIButton的颜色。

enter image description here

有什么方法可以根据放置在UIButton中的图像更改UIImageView的颜色吗?

1 个答案:

答案 0 :(得分:0)

这是扩展名,用于根据其选择的状态,正常或突出显示来设置UIButton的背景色

extension UIButton {

    func setBackgroundColor(color: UIColor, forState: UIControl.State) {
        self.clipsToBounds = true  // add this to maintain corner radius
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.setBackgroundImage(colorImage, for: forState)
        }
    }

}

,您还可以将按钮的颜色设置为“喜欢”

loginButton.tintColor = .red
相关问题