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

问题描述 投票:2回答:4

我可以使用以下代码将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活动重置其颜色。

ios uiimageview uibutton swift3 mask
4个回答
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

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


0
投票

你能尝试一下这对我有用吗?

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

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

© www.soinside.com 2019 - 2024. All rights reserved.