Changing color of image embedded to a button (Swift3)

二次信任 提交于 2019-12-24 02:34:13

问题


I am able to change the color of an image of a UIButton from black to white with the following code:

extension UIImage {
    func maskWith(color: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)

        let context = UIGraphicsGetCurrentContext()!
        context.translateBy(x: 0, y: size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.setBlendMode(.normal)

        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        context.clip(to: rect, mask: cgImage!)

        color.setFill()
        context.fill(rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()!

        UIGraphicsEndImageContext()

    return newImage
    }
}

I am setting the color of the image of the UIButton using the following:

//creditCardBtn is the the button variable
creditCardBtn.imageView?.image? = (creditCardBtn.imageView?.image?.maskWith(color: .white))!

My Issue When the user sets their finger on the button and then slowly drags their finger away, the image color resets itself. My thought was to use an @IBAction and reset the UIButton's image when there is a Touch Up Inside. However this did not prevent the image from resetting its color.

Here is the code I tried:

@IBAction func creditCardTap(_ sender: UIButton) {
    creditCardBtn.imageView?.image?.maskWith(color: .white)
}

What I am looking for: How to prevent the button from resetting its color from UI activities.


回答1:


Here's a simpler way to do this without any extension and without resetting the color on touch:

let stencil = myImage.withRenderingMode(.alwaysTemplate) // use your UIImage here
myButton.setImage(stencil, for: .normal) // assign it to your UIButton
myButton.tintColor = UIColor.white // set a color



回答2:


  //works in func tableView(_ tableView: UITableView, cellForRowAt IndexPath: IndexPath) -> UITableViewCell

if redButton == true {
        let stencil = UIImage(named: "phoneCircle.png")?.withRenderingMode(.alwaysTemplate)
        cell.patientCTCallButton.setImage(stencil, for: .normal)
        cell.patientCTCallButton.tintColor = .red // set a color
}




回答3:


Can you try this it's working for me.

let image = UIImage(named: "menu")
    let tintedImage = image?.withRenderingMode(.alwaysTemplate)
    mapMenuButton.setImage(tintedImage, for: .normal)
    mapMenuButton.tintColor = UIColor.appThemeColor()



回答4:


swift 4 and 4.2

let img = UIImage.init(named: "buttonName")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
            btn.setImage(img, for: .normal)
            btn.tintColor = .gray

}



来源:https://stackoverflow.com/questions/41352576/changing-color-of-image-embedded-to-a-button-swift3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!