更改嵌入按钮的图像颜色(Swift3)

时间:2016-12-27 21:45:04

标签: ios uiimageview uibutton swift3 mask

我可以使用以下代码将UIButton的图像颜色从黑色更改为白色:

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
    }
}

我正在使用以下内容设置UIButton图像的颜色:

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

我的问题 当用户将手指放在按钮上然后慢慢地将手指拖开时,图像颜色会自行重置。我的想法是使用@IBAction并在有UIButton时重置Touch Up Inside的图片。但是,这并不能阻止图像重置其颜色。

这是我尝试过的代码:

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

我在寻找什么: 如何防止按钮从UI活动中重置其颜色。

4 个答案:

答案 0 :(得分:7)

这是一种更简单的方法,无需任何扩展即可完成此操作,并且无需重置触摸颜色:

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

答案 1 :(得分:0)

  //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
}

white "phoneCircle.png" before colored red enter image description here

答案 2 :(得分:0)

你可以尝试一下它为我工作吗。

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

答案 3 :(得分:0)

迅速4和4.2

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

}

enter image description here