改变颜色嵌入到一个按钮(Swift3)
问题描述:
我能够从黑UIButton
的图像的颜色改变为白色用下面的代码:改变颜色嵌入到一个按钮(Swift3)
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
+0
+1使代码更加简单,无需扩展,然后再提供一个解决方案,避免我必须重置UI事件的颜色。谢谢 – Sami
答
//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
}
答
你可以试试这个它是为我工作。
let image = UIImage(named: "menu")
let tintedImage = image?.withRenderingMode(.alwaysTemplate)
mapMenuButton.setImage(tintedImage, for: .normal)
mapMenuButton.tintColor = UIColor.appThemeColor()
您是否尝试过使用按钮上的其他操作事件?也许触摸下,触摸拖动退出或触摸取消? – ThePringle
我刚刚尝试过'在退出时完成,'取消触摸','向下触摸','触摸拖动退出'和'向上触摸内部'。当用户进行UI活动时,颜色仍然在变化。 – Sami