如何将tintColor应用于UIImage?

时间:2013-11-06 02:29:43

标签: ios objective-c uibutton uiimage

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

8 个答案:

答案 0 :(得分:70)

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

本文涵盖:

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

如果您需要支持早期版本,可能需要考虑此主题

How would I tint an image programmatically on the iPhone?

答案 1 :(得分:3)

快速4,复制粘贴解决方案

import cv2
import numpy as np

image = cv2.imread("1.png")

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

blur = cv2.blur(gray,(3,3))

_,thresh = cv2.threshold(blur,240,255,cv2.THRESH_BINARY)
cv2.imshow("thresh",thresh)

thresh = cv2.bitwise_not(thresh)

element = cv2.getStructuringElement(shape=cv2.MORPH_RECT, ksize=(5, 5))

erode = cv2.erode(thresh,element,3)
cv2.imshow("erode",erode)

cv2.imshow("img",image)
cv2.waitKey(0)
cv2.destroyAllWindows()

答案 2 :(得分:3)

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

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

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

答案 3 :(得分: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
}

答案 4 :(得分:2)

尝试一下:

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)

答案 5 :(得分:0)

为什么不使用图像过滤

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中

答案 6 :(得分:0)

使用此简单的UIImageView扩展

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

答案 7 :(得分:0)

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)