62

我有一个UIImage全黑的小符号。UIImage正在设置在我拥有的自定义子UIButton类中。是否可以让图像应用tintColor到它,所以它不是黑色图像而是将颜色更改为任何颜色tintColor

我只是想避免创建新资产。

// here I want defaultImageName (that is black) to use the tintColor (that is white)
[self setImage:[UIImage imageNamed:defaultImageName] forState:UIControlStateNormal];
4

8 回答 8

78

如果您只支持 iOS 7,则可以使用tintColorUIImageRenderingModeAlwaysTemplate

本文涵盖:

https://www.captechconsulting.com/blogs/ios-7-tutorial-series-tint-color-and-easy-app-theming

如果您需要支持早期版本,您可能需要考虑这个线程

如何在 iPhone 上以编程方式为图像着色?

于 2013-11-06T02:39:24.253 回答
21

Swift 4,复制粘贴解决方案

@IBOutlet weak var iconImageView: UIImageView!
iconImageView.image = UIImage(imageLiteralResourceName: "myImageName").withRenderingMode(.alwaysTemplate)
iconImageView.tintColor = UIColor.red
于 2019-01-16T09:20:01.403 回答
7

在 iOS 13+ 上,您可以使用以下内容:

UIImage(named: "img_name")?.withTintColor(.red)

https://developer.apple.com/documentation/uikit/uiimage/3327300-withtintcolor

于 2020-07-20T09:08:06.643 回答
5

尝试这个:

func tinted(with color: UIColor) -> UIImage? {
    defer { UIGraphicsEndImageContext() }
    UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
    color.set()
    self.withRenderingMode(.alwaysTemplate).draw(in: CGRect(origin: .zero, size: self.size))
    return UIGraphicsGetImageFromCurrentImageContext()
}

例如:

button.setImage(UIImage(systemName: "checkmark.circle")?.tinted(with: .systemGray), for: .normal)
于 2020-07-06T09:06:05.850 回答
2

以下是我在 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
}
于 2016-06-07T13:14:41.490 回答
1

Swift5 扩展

extension UIImage {
    var template: UIImage? {
         return self.withRenderingMode(.alwaysTemplate)
    }
}

用法

  • UIImageView

    let imgView = UIImageView()
    imgView.tintColor = UIColor.red
    imgView.image = UIImage(named: "IMAGE_NAME_HERE")?.template
    
  • 用户界面按钮

    let button = UIButton(type: .custom)
    button.tintColor = UIColor.red
    button.setImage(UIImage(named: "IMAGE_NAME_HERE")?.template, for: .normal)
    
于 2020-11-09T19:40:27.170 回答
1

为什么不使用图像过滤

btn.setImage(image, for: UIControl.State.normal)
btn.setImage(image.disabled, for: UIControl.State.disabled)

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

当然,在 Swift 5

于 2019-11-06T02:39:51.013 回答
0

使用这个简单的 UIImageView 扩展

@IBInspectable var tintedColor: UIColor{
    get{
        return tintColor
    }
    set{
        image = image?.withRenderingMode(.alwaysTemplate)
        tintColor = newValue
    }
}
于 2020-03-16T19:10:07.267 回答