ios 如何将 tintColor 应用于 UIImage?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/19802982/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to apply a tintColor to a UIImage?
提问by aahrens
I have a UIImagethat is a small symbol that is all black. The UIImageis getting set in a custom UIButtonsubclass I have. Is it possible to have the image to apply the tintColorto it, so instead of the black image it changes colors to whatever the tintColoris?
我有一个UIImage全黑的小符号。将UIImage在自定义设置得到UIButton的子类我。是否可以将图像应用于tintColor它,而不是黑色图像,它会将颜色更改为任何颜色tintColor?
I'm just trying to avoid creating new assets.
我只是想避免创建新资产。
// here I want defaultImageName (that is black) to use the tintColor (that is white)
[self setImage:[UIImage imageNamed:defaultImageName] forState:UIControlStateNormal];
回答by madmik3
If you are just supporting iOS 7 you can use tintColorand UIImageRenderingModeAlwaysTemplate
如果您只支持 iOS 7,则可以使用tintColor和UIImageRenderingModeAlwaysTemplate
This article covers that:
本文涵盖:
https://www.captechconsulting.com/blogs/ios-7-tutorial-series-tint-color-and-easy-app-theming
https://www.captechconsulting.com/blogs/ios-7-tutorial-series-tint-color-and-easy-app-theming
If you need to support an earlier version you may want to consider this thread
如果您需要支持早期版本,您可能需要考虑这个线程
回答by zgorawski
Swift 4, copy-paste solution
Swift 4、复制粘贴解决方案
@IBOutlet weak var iconImageView: UIImageView!
iconImageView.image = UIImage(imageLiteralResourceName: "myImageName").withRenderingMode(.alwaysTemplate)
iconImageView.tintColor = UIColor.red
回答by J-Dizzle
Here's how I use tint colors and opacities in IOS 9 with Swift -
这是我在 IOS 9 中使用 Swift 使用色调颜色和不透明度的方法 -
//apply a color to an image
//ref - http://stackoverflow.com/questions/28427935/how-can-i-change-image-tintcolor
//ref - https://www.captechconsulting.com/blogs/ios-7-tutorial-series-tint-color-and-easy-app-theming
func getTintedImage() -> UIImageView {
    var image :UIImage
    var imageView :UIImageView
    image = UIImage(named: "someAsset")!
    let size  : CGSize = image.size
    let frame : CGRect = CGRectMake((UIScreen.mainScreen().bounds.width-86)/2, 600, size.width, size.height)
    let redCover : UIView = UIView(frame: frame)
    redCover.backgroundColor = UIColor.redColor()
    redCover.layer.opacity = 0.75
    imageView = UIImageView();
    imageView.image = image.imageWithRenderingMode(UIImageRenderingMode.Automatic)
    imageView.addSubview(redCover)
    return imageView
}
回答by black_pearl
Why not use image filtering
为什么不使用图像过滤
btn.setImage(image, for: UIControl.State.normal)
btn.setImage(image.disabled, for: UIControl.State.disabled)
Use CoreImage to do image filter
使用 CoreImage 做图片滤镜
extension UIImage
{
    /// Create a grayscale image with alpha channel. Is 5 times faster than grayscaleImage().
    /// - Returns: The grayscale image of self if available.
    var disabled: UIImage?
    {
        // Create image rectangle with current image width/height * scale
        let pixelSize = CGSize(width: self.size.width * self.scale, height: self.size.height * self.scale)
        let imageRect = CGRect(origin: CGPoint.zero, size: pixelSize)
        // Grayscale color space
         let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray()
            // Create bitmap content with current image size and grayscale colorspace
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
        if let context: CGContext = CGContext(data: nil, width: Int(pixelSize.width), height: Int(pixelSize.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
            {
                // Draw image into current context, with specified rectangle
                // using previously defined context (with grayscale colorspace)
                guard let cg = self.cgImage else{
                    return nil
                }
                context.draw(cg, in: imageRect)
                // Create bitmap image info from pixel data in current context
                if let imageRef: CGImage = context.makeImage(){
                    let bitmapInfoAlphaOnly = CGBitmapInfo(rawValue: CGImageAlphaInfo.alphaOnly.rawValue)
                    guard let context = CGContext(data: nil, width: Int(pixelSize.width), height: Int(pixelSize.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfoAlphaOnly.rawValue) else{
                        return nil
                    }
                    context.draw(cg, in: imageRect)
                    if let mask: CGImage = context.makeImage() {
                        // Create a new UIImage object
                        if let newCGImage = imageRef.masking(mask){
                            // Return the new grayscale image
                            return UIImage(cgImage: newCGImage, scale: self.scale, orientation: self.imageOrientation)
                        }
                    }
                }
            }
        // A required variable was unexpected nil
        return nil
    }
}
Of course, in Swift 5
当然,在 Swift 5 中
回答by Milind Chaudhary
Use this simple extension to UIImageView
使用这个简单的 UIImageView 扩展
@IBInspectable var tintedColor: UIColor{
    get{
        return tintColor
    }
    set{
        image = image?.withRenderingMode(.alwaysTemplate)
        tintColor = newValue
    }
}

