更改嵌入按钮的图像的颜色(Swift3) [英] Changing color of image embedded to a button (Swift3)

查看:112
本文介绍了更改嵌入按钮的图像的颜色(Swift3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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))!

我的问题 当用户将手指放在按钮上,然后慢慢将其手指拉开时,图像颜色将重置.我的想法是使用@IBAction并在出现Touch Up Inside时重置UIButton的图像.但是,这并不能防止图像重置其颜色.

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.

这是我尝试的代码:

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

我在寻找什么 如何防止按钮通过UI活动重置其颜色.

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

推荐答案

这是一种更简单的方法,无需任何扩展,也无需重置触摸时的颜色:

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

这篇关于更改嵌入按钮的图像的颜色(Swift3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆