如何将tintColor应用于UIImage?

2020/12/01 04:22 · ios ·  · 0评论

我有一个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];

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

本文涵盖:

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

如果您需要支持早期版本,则可能需要考虑使用此线程

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

Swift 4,复制粘贴解决方案

@IBOutlet weak var iconImageView: UIImageView!
iconImageView.image = UIImage(imageLiteralResourceName: "myImageName").withRenderingMode(.alwaysTemplate)
iconImageView.tintColor = UIColor.red

这是我在Swift 9的IOS 9中使用色彩和不透明性的方法-

//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
}

在iOS 13+上,您可以使用以下命令:

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

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

试试这个:

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)

为什么不使用图像过滤

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中

使用这个简单的扩展UIImageView

@IBInspectable var tintedColor: UIColor{
    get{
        return tintColor
    }
    set{
        image = image?.withRenderingMode(.alwaysTemplate)
        tintColor = newValue
    }
}

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
    
  • UIButton

    let button = UIButton(type: .custom)
    button.tintColor = UIColor.red
    button.setImage(UIImage(named: "IMAGE_NAME_HERE")?.template, for: .normal)
    
本文地址:http://ios.askforanswer.com/ruhejiangtintcoloryingyongyuuiimage.html
文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!