I noticed that when I place a white or black UIImage into a UISegmentedControl it automatically color masks it to match the tint of the segmented control. I thought this was really cool, and was wondering if I could do this elsewhere as well. For example, I have a bunch of buttons that have a uniform shape but varied colors. Instead of making a PNG for each button, could I somehow use this color masking to use the same image for all of them but then set a tint color or something to change their actual color?


当前回答

斯威夫特3.0

    let image = UIImage(named:"NoConnection")!

 warningButton = UIButton(type: .system)        
    warningButton.setImage(image, for: .normal)
    warningButton.tintColor = UIColor.lightText
    warningButton.frame = CGRect(origin: CGPoint(x:-100,y:0), size: CGSize(width: 59, height: 56))

    self.addSubview(warningButton)

其他回答

为了在按钮上设置白色的图像(箭头图标),我们使用:

let imageOnButton = UIImage(named: "navForwardArrow")?.imageWithColor(color: UIColor.white)
button.setImage(imageOnButton, for: .normal)

已知问题:当按下按钮时,图标会失去白色。

截图:

斯威夫特3:

如果你已经通过xCode界面构建器设置了你的图像,这个解决方案可能会很舒服。基本上你有一个扩展来着色图像:

extension UIImage {
    public func image(withTintColor color: UIColor) -> UIImage{
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        let context: CGContext = UIGraphicsGetCurrentContext()!
        context.translateBy(x: 0, y: self.size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.setBlendMode(CGBlendMode.normal)
        let rect: CGRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
        context.clip(to: rect, mask: self.cgImage!)
        color.setFill()
        context.fill(rect)
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }
}

然后,你可以准备这个UIButton扩展为特定状态的图像上色:

extension UIButton {
    func imageWith(color:UIColor, for: UIControlState) {
        if let imageForState = self.image(for: state) {
            self.image(for: .normal)?.withRenderingMode(.alwaysTemplate)
            let colorizedImage = imageForState.image(withTintColor: color)
            self.setImage(colorizedImage, for: state)
        }
    }
}

用法:

myButton.imageWith(.red, for: .normal)

P.S.(在表格单元格中工作也很好,你不需要调用setNeedDisplay()方法,由于UIImage扩展,颜色的变化是立即的。

正如Ric已经在他的帖子中提到的,你可以在代码中设置渲染模式,你也可以直接在图像目录中这样做,见下面所附的图像。只需要设置渲染为模板图像

注意,我在使用iOS 7和这种方法时遇到过问题。如果你也使用iOS 7,你可能也想在代码中完成,就像这里描述的。

let button = UIButton(type: .custom)
let image = UIImage(named: "image_name")?.withRenderingMode(.alwaysTemplate)
button.setImage(image, for: .normal)
button.tintColor = UIColor.red

如果你在设置UIButton。tintColor by UIColor(r:g:b:alpha:),记住值除以255。这些RGB值应该在0和1之间。

自定义按钮以各自的图像颜色显示。在故事板中将按钮类型设置为“System”(或者在代码中设置为UIButtonTypeSystem),将以默认的色调呈现按钮的图像。

(在iOS9, Xcode 7.3上测试)