gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:05:44 24 4
gpt4 key购买 nike

我可以使用以下代码将 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 并在有 Touch Up Inside 时重置 UIButton 的图像。然而,这并没有阻止图像重置其颜色。

这是我试过的代码:

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

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

最佳答案

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

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

关于ios - 更改嵌入按钮的图像颜色(Swift3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41352576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com