【问题标题】:How can I change image tintColor in iOS and WatchKit如何在 iOS 和 WatchKit 中更改图像 tintColor
【发布时间】:2013-10-16 23:23:52
【问题描述】:

我有一个名为“theImageView”的 UIImageView,UIImage 是单一颜色的(透明背景),就像下面的左黑心一样。如何根据 iOS 7+ 导航栏图标中使用的 tint 方法在 iOS 7 或更高版本中以编程方式更改此图像的色调颜色?

此方法是否也适用于 Apple Watch 应用的 WatchKit?

【问题讨论】:

  • “以下代码错误”是什么意思,设置UIImageUIImageRenderingModeAlwaysTemplate,然后设置UIImageVIewtintColor 确实有效。 (在我的代码中^^)
  • 使用透明的 png like this one
  • 你真的应该把你的答案移到答案部分,因为我认为这是最好的和最现代的。

标签: ios swift uiimage uicolor watchkit


【解决方案1】:

这是一个可以解决问题的类别

@interface UIImage(Overlay)
@end

@implementation UIImage(Overlay)

- (UIImage *)imageWithColor:(UIColor *)color1
{
        UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(context, 0, self.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextSetBlendMode(context, kCGBlendModeNormal);
        CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
        CGContextClipToMask(context, rect, self.CGImage);
        [color1 setFill];
        CGContextFillRect(context, rect);
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
}
@end

所以你会这样做:

theImageView.image = [theImageView.image imageWithColor:[UIColor redColor]];

【讨论】:

  • 感谢这个非常有效的答案,我想我的代码从一开始就没有问题,我应该回答我自己的问题并给你一个 +1 无论如何..
【解决方案2】:

我必须在 Swift 中使用 extension 来执行此操作。

我想我会分享我是如何做到的:

extension UIImage {
    func imageWithColor(color1: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        color1.setFill()

        let context = UIGraphicsGetCurrentContext() as CGContextRef
        CGContextTranslateCTM(context, 0, self.size.height)
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextSetBlendMode(context, CGBlendMode.Normal)

        let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
        CGContextClipToMask(context, rect, self.CGImage)
        CGContextFillRect(context, rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
        UIGraphicsEndImageContext()

        return newImage
    }
}

用法:

theImageView.image = theImageView.image.imageWithColor(UIColor.redColor())

斯威夫特 4

extension UIImage {
    func imageWithColor(color1: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        color1.setFill()

        let context = UIGraphicsGetCurrentContext()
        context?.translateBy(x: 0, y: self.size.height)
        context?.scaleBy(x: 1.0, y: -1.0)
        context?.setBlendMode(CGBlendMode.normal)

        let rect = CGRect(origin: .zero, size: CGSize(width: self.size.width, height: self.size.height))
        context?.clip(to: rect, mask: self.cgImage!)
        context?.fill(rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }
}

用法:

theImageView.image = theImageView.image?.imageWithColor(color1: UIColor.red)

【讨论】:

  • 仅供参考,直到我将 color1.setFill() 移动到方法 UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) 的第一行正下方,这对我不起作用。
  • @Aaron 根据您的评论更新。谢谢。
  • @CeceXX 改用CGBlendMode.Normal
  • 你太棒了,但是你可能需要把它改成 Swift 3
  • @SimpiMind 提供了 Swift 4。
【解决方案3】:

试试这个

http://robots.thoughtbot.com/designing-for-ios-blending-modes

- (void)viewDidLoad
{
[super viewDidLoad];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 300, 50)];
label.numberOfLines = 0;
label.font = [UIFont systemFontOfSize:13];
label.text = @"These checkmarks use the same gray checkmark image with a tintColor applied to the image view";
[self.view addSubview:label];

[self _createImageViewAtY:100 color:[UIColor purpleColor]];
}

- (void)_createImageViewAtY:(int)y color:(UIColor *)color {
UIImage *image = [[UIImage imageNamed:@"gray checkmark.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect frame = imageView.frame;
frame.origin.x = 100;
frame.origin.y = y;
imageView.frame = frame;

if (color)
    imageView.tintColor = color;

[self.view addSubview:imageView];
}

【讨论】:

    【解决方案4】:

    iOS
    对于 iOS 应用,在 Swift 3、4 或 5 中:

    theImageView.image = theImageView.image?.withRenderingMode(.alwaysTemplate)
    theImageView.tintColor = UIColor.red
    

    对于 Swift 2:

    theImageView.image = theImageView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
    theImageView.tintColor = UIColor.redColor()
    

    同时,现代的 Objective-C 解决方案是:

    theImageView.image = [theImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [theImageView setTintColor:[UIColor redColor]];
    

    Watchkit
    在 Apple Watch 应用程序的 WatchKit 中,您可以设置 tint color for a template image

    1. 您必须将图像添加到 WatchKit 应用程序的资产目录中,并在属性检查器中设置要呈现为模板图像的图像集。与 iPhone 应用不同的是,目前 WatchKit Extension 中无法在代码中设置模板渲染。
    2. 在应用的界面构建器中设置要在 WKInterfaceImage 中使用的图像
    3. 在 WKInterfaceController 中为名为“theImage”的 WKInterfaceImage 创建一个 IBOutlet...

    然后在 Swift 3 或 4 中设置色调颜色:

    theImage.setTintColor(UIColor.red)
    

    斯威夫特 2:

    theImage.setTintColor(UIColor.redColor())
    

    然后在 Objective-C 中设置 tint 颜色:

    [self.theImage setTintColor:[UIColor redColor]];
    

    如果您使用模板图像并且未应用色调颜色,则会应用您的 WatchKit 应用的全局色调。如果您没有设置全局色调,theImage 用作模板图像时默认为浅蓝色。

    【讨论】:

    • 这是最好最简单的解决方案。
    • imageWithRenderingMode 太慢了。在故事板和图像资产中。您也可以更改这两个:将渲染模式更新为模板图像 - 这是一个更好的解决方案
    • 完美,现在我在您的代码中使用此方法: + (UIImageView ) tintImageView: (UIImageView *)imageView withColor: (UIColor) color{ imageView.image = [ imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; [imageView setTintColor:color];返回图像视图; }
    • 图像黑色更好吗?
    • @Bruno 图像不需要是黑色的,不。适用于任何颜色。
    【解决方案5】:

    使用斯威夫特

    let commentImageView = UIImageView(frame: CGRectMake(100, 100, 100, 100))
    commentImageView.image = UIImage(named: "myimage.png")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
    commentImageView.tintColor = UIColor.blackColor()
    addSubview(commentImageView)
    

    【讨论】:

    • 你可以简单地输入.AlwaysTemplate
    • 是的,它确实缩短了代码,但似乎它可能会降低代码的清晰度。因此不确定点快捷方式
    • 我看到你的 POV,只是另一种选择。
    【解决方案6】:

    在故事板和图像资源中。你也可以改变这两个:

    将渲染模式更新为模板图像

    更新视图中的色调颜色。

    【讨论】:

    • 这真的是最糟糕的答案!
    • 从情节提要中设置此值对我来说永远不起作用。我总是必须使用代码中的imageView.tintColor
    • @KamilPowałowski 对我来说这有时会起作用......我不知道为什么。我希望我知道为什么它并不总是有效。所以我最终通过代码来完成
    • 对我来说,这个故事板方法适用于按钮,但不适用于 imageViews。我仍然需要在 imageViews 的代码中设置 tintColor。
    • 如果有人还在摸不着头脑想知道为什么它在 IB 中不起作用,请尝试将 imageView 的 Opaque 设置为 No。
    【解决方案7】:

    斯威夫特 4

    更改 UIImage SVG / PDF 的色调,适用于具有独特颜色的图像

    import Foundation
        
    // MARK: - UIImage extensions
    
    public extension UIImage {
    
        //
        /// Tint Image
        ///
        /// - Parameter fillColor: UIColor
        /// - Returns: Image with tint color
        func tint(with fillColor: UIColor) -> UIImage? {
            let image = withRenderingMode(.alwaysTemplate)
            UIGraphicsBeginImageContextWithOptions(size, false, scale)
            fillColor.set()
            image.draw(in: CGRect(origin: .zero, size: size))
    
            guard let imageColored = UIGraphicsGetImageFromCurrentImageContext() else {
                return nil
            }
            
            UIGraphicsEndImageContext()
            return imageColored
        }
    }
    

    更改 UIImageView 的色调,适用于具有独特颜色的图像

    let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 50, height: 50))
    imageView.image = UIImage(named: "hello.png")!.withRenderingMode(.alwaysTemplate)
    imageView.tintColor = .yellow
    

    picture 更改 UIImage 的色调,使用它:

    import Foundation
    
    // MARK: - Extensions UIImage
    
    public extension UIImage {
    
        /// Tint, Colorize image with given tint color
        /// This is similar to Photoshop's "Color" layer blend mode
        /// This is perfect for non-greyscale source images, and images that 
        /// have both highlights and shadows that should be preserved<br><br>
        /// white will stay white and black will stay black as the lightness of 
        /// the image is preserved
        ///
        /// - Parameter TintColor: Tint color
        /// - Returns:  Tinted image
        public func tintImage(with fillColor: UIColor) -> UIImage {
            
            return modifiedImage { context, rect in
                // draw black background - workaround to preserve color of partially transparent pixels
                context.setBlendMode(.normal)
                UIColor.black.setFill()
                context.fill(rect)
                
                // draw original image
                context.setBlendMode(.normal)
                context.draw(cgImage!, in: rect)
                
                // tint image (loosing alpha) - the luminosity of the original image is preserved
                context.setBlendMode(.color)
                fillColor.setFill()
                context.fill(rect)
                
                // mask by alpha values of original image
                context.setBlendMode(.destinationIn)
                context.draw(context.makeImage()!, in: rect)
            }
        }
        
        /// Modified Image Context, apply modification on image
        ///
        /// - Parameter draw: (CGContext, CGRect) -> ())
        /// - Returns:        UIImage
        fileprivate func modifiedImage(_ draw: (CGContext, CGRect) -> ()) -> UIImage {
            
            // using scale correctly preserves retina images
            UIGraphicsBeginImageContextWithOptions(size, false, scale)
            let context: CGContext! = UIGraphicsGetCurrentContext()
            assert(context != nil)
            
            // correctly rotate image
            context.translateBy(x: 0, y: size.height)
            context.scaleBy(x: 1.0, y: -1.0)
            
            let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
            
            draw(context, rect)
            
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image!
        }
    }
    

    【讨论】:

    • 嘿,我是 swift 的新手,但你在这里告诉它是用于 SVG 图像的,但我找不到将 SVG 解析为 UIImage 的方法,你能帮我吗?或者也许我可以用SVG正确处理这个问题。谢谢!
    • @DumitruRogojinaru 在资产中使用带有模板图像的 SVG 函数
    • Swift 4 更新
    【解决方案8】:

    现在我使用基于 Duncan Babbage 响应的这种方法:

    + (UIImageView *) tintImageView: (UIImageView *)imageView withColor: (UIColor*) color{
        imageView.image = [imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [imageView setTintColor:color];
        return imageView;
    }
    

    【讨论】:

      【解决方案9】:

      为了快速 3 个目的

      theImageView.image = theImageView.image!.withRenderingMode(.alwaysTemplate)
      theImageView.tintColor = UIColor.red
      

      【讨论】:

        【解决方案10】:

        如果你有一个图像来替换清除按钮,你可以在 Swift 3 中使用它

        func addTextfieldRightView(){
        
            let rightViewWidth:CGFloat = 30
        
            let viewMax = self.searchTxt.frame.height
            let buttonMax = self.searchTxt.frame.height - 16
        
            let buttonView = UIView(frame: CGRect(
                x: self.searchTxt.frame.width - rightViewWidth,
                y: 0,
                width: viewMax,
                height: viewMax))
        
            let myButton = UIButton(frame: CGRect(
                x: (viewMax - buttonMax) / 2,
                y: (viewMax - buttonMax) / 2,
                width: buttonMax,
                height: buttonMax))
        
            myButton.setImage(UIImage(named: "BlueClear")!, for: .normal)
        
            buttonView.addSubview(myButton)
        
            let clearPressed = UITapGestureRecognizer(target: self, action: #selector(SearchVC.clearPressed(sender:)))
            buttonView.isUserInteractionEnabled = true
            buttonView.addGestureRecognizer(clearPressed)
        
            myButton.addTarget(self, action: #selector(SearchVC.clearPressed(sender:)), for: .touchUpInside)
        
            self.searchTxt.rightView = buttonView
            self.searchTxt.rightViewMode = .whileEditing
        }
        

        【讨论】:

          【解决方案11】:

          利用 Swift 中的扩展:-

          extension UIImageView {
              func changeImageColor( color:UIColor) -> UIImage
              {
                  image = image!.withRenderingMode(.alwaysTemplate)
                  tintColor = color
                  return image!
              }
          }
          
             //Change color of logo 
             logoImage.image =  logoImage.changeImageColor(color: .red)
          

          【讨论】:

            【解决方案12】:

            如果有人关心没有UIImageView 的解决方案:

            // (Swift 3)
            extension UIImage {
                func tint(with color: UIColor) -> UIImage {
                    var image = withRenderingMode(.alwaysTemplate)
                    UIGraphicsBeginImageContextWithOptions(size, false, scale)
                    color.set()
            
                    image.draw(in: CGRect(origin: .zero, size: size))
                    image = UIGraphicsGetImageFromCurrentImageContext()!
                    UIGraphicsEndImageContext()
                    return image
                }
            }
            

            【讨论】:

            • 哇,在搜索了一个多小时后,效果就像魔术一样。需要:将 NSTextAttachment 中的图标设置为与图标原始颜色不同的颜色。使用 UIImageView 并更改其 tintColor 的标准答案在这里不起作用,因为 NSTextAttachment 不采用 UIImageView。
            • 这是迄今为止我发现的最好的解决方案,特别是对于任何寻找与 Swift 3 兼容的代码的人。很棒的建议!
            【解决方案13】:

            也可以从代码和 Interface Builder 中使用的子类:

            @implementation TintedImageView
            
            - (instancetype)initWithFrame:(CGRect)frame {
                self = [super initWithFrame:frame];
                if (self) {
                    [self setup];
                }
                return self;
            }
            
            - (instancetype)initWithCoder:(NSCoder *)aDecoder {
                self = [super initWithCoder:aDecoder];
                if (self) {
                    [self setup];
                }
                return self;
            }
            
            -(void)setup {
                self.image = [self.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            }
            
            @end
            

            【讨论】:

              【解决方案14】:

              iOS

              从 Interface Builder 执行此操作的解决方案,set templateImage param in keyPath 并从 IB 中选择您的色调

              extension UIImageView {
              
              // make template image with tint color
              var templateImage: Bool {
                  set {
                      if newValue, let image = self.image {
                          let newImage = image.withRenderingMode(.alwaysTemplate)
                          self.image = newImage
                      }
                  } get {
                      return false
                  }
              }
              

              }

              【讨论】:

                【解决方案15】:

                这是我的 UIImage 扩展,你可以直接对图像使用 changeTintColor 函数。

                extension UIImage {
                
                    func changeTintColor(color: UIColor) -> UIImage {
                        var newImage = self.withRenderingMode(.alwaysTemplate)
                        UIGraphicsBeginImageContextWithOptions(self.size, false, newImage.scale)
                        color.set()
                        newImage.draw(in: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height))
                        newImage = UIGraphicsGetImageFromCurrentImageContext()!
                        UIGraphicsEndImageContext()
                        return newImage
                    }
                
                    func changeColor(color: UIColor) -> UIImage {
                        let backgroundSize = self.size
                        UIGraphicsBeginImageContext(backgroundSize)
                        guard let context = UIGraphicsGetCurrentContext() else {
                            return self
                        }
                        var backgroundRect = CGRect()
                        backgroundRect.size = backgroundSize
                        backgroundRect.origin.x = 0
                        backgroundRect.origin.y = 0
                
                        var red: CGFloat = 0
                        var green: CGFloat = 0
                        var blue: CGFloat = 0
                        var alpha: CGFloat = 0
                        color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
                        context.setFillColor(red: red, green: green, blue: blue, alpha: alpha)
                        context.translateBy(x: 0, y: backgroundSize.height)
                        context.scaleBy(x: 1.0, y: -1.0)
                        context.clip(to: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height),
                                 mask: self.cgImage!)
                        context.fill(backgroundRect)
                
                        var imageRect = CGRect()
                        imageRect.size = self.size
                        imageRect.origin.x = (backgroundSize.width - self.size.width) / 2
                        imageRect.origin.y = (backgroundSize.height - self.size.height) / 2
                
                        context.setBlendMode(.multiply)
                        context.draw(self.cgImage!, in: imageRect)
                
                        let newImage = UIGraphicsGetImageFromCurrentImageContext()
                        UIGraphicsEndImageContext()
                        return newImage!
                    }
                
                }
                

                这样的用法示例

                let image = UIImage(named: "sample_image")
                imageView.image = image.changeTintColor(color: UIColor.red)
                

                你可以使用changechangeColor函数来改变图像颜色

                【讨论】:

                  【解决方案16】:

                  来自 fuzz

                  的 Swift 3 版本的扩展答案
                  func imageWithColor(color: UIColor) -> UIImage {
                      UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
                      color.setFill()
                  
                      let context = UIGraphicsGetCurrentContext()! as CGContext
                      context.translateBy(x: 0, y: self.size.height)
                      context.scaleBy(x: 1.0, y: -1.0);
                      context.setBlendMode(.normal)
                  
                      let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect
                      context.clip(to: rect, mask: self.cgImage!)
                      context.fill(rect)
                  
                      let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage
                      UIGraphicsEndImageContext()
                  
                      return newImage
                  }
                  

                  【讨论】:

                    【解决方案17】:

                    profileImageView.image = theImageView.image!.withRenderingMode(.alwaysTemplate)
                    profileImageView.tintColor = UIColor.green

                    首先选择图像资产中的特定图像,然后选择红色作为模板而不是默认,然后在该写入行之后。 profileImageView.tintColor = UIColor.green

                    【讨论】:

                      【解决方案18】:

                      用于为 UIButton 的图像着色

                      let image1 = "ic_shopping_cart_empty"
                      btn_Basket.setImage(UIImage(named: image1)?.withRenderingMode(.alwaysTemplate), for: .normal)
                      btn_Basket.setImage(UIImage(named: image1)?.withRenderingMode(.alwaysTemplate), for: .selected)
                      btn_Basket.imageView?.tintColor = UIColor(UIColor.Red)
                      

                      【讨论】:

                        【解决方案19】:

                        如果您有 SVG 图像的任何 ID,则可以根据 ID 填充颜色。

                            let image = SVGKImage(named: "iconName")
                            let svgIMGV = SVGKFastImageView(frame: self.imgView.frame)
                                 svgIMGV.image = image
                                  svgIMGV.fillTintColor(colorImage: UIColor.red, iconID: "Bank")
                        
                        // Add in extension SVGKImageView
                        extension SVGKImageView {
                         func fillTintColor(colorImage: UIColor, iconID: String) {
                                if self.image != nil && self.image.caLayerTree != nil {
                                    print(self.image.caLayerTree.sublayers)
                                    guard let sublayers = self.image.caLayerTree.sublayers else { return }
                                    fillRecursively(sublayers: sublayers, color: colorImage, iconID: iconID)
                                }
                            }
                        
                             private func fillRecursively(sublayers: [CALayer], color: UIColor, iconID: String, hasFoundLayer: Bool) {
                                var isLayerFound = false
                                for layer in sublayers {
                                    if let l = layer as? CAShapeLayer {
                        
                                        print(l.name)                
                                        //IF you want to color the specific shapelayer by id else remove the l.name  == "myID"  validation
                                        if let name =  l.name,  hasFoundLayer == true && name == "myID" {
                                            self.colorThatImageWIthColor(color: color, layer: l)
                                            print("Colouring FInished")
                                        }
                                    } else {
                                        if layer.name == iconID {
                                            if let innerSublayer = layer.sublayers as? [CAShapeLayer] {
                                                fillRecursively(sublayers: innerSublayer, color: color, iconID: iconID, hasFoundLayer: true )
                                                print("FOund")
                                            }
                                        } else {
                                            if let l = layer as? CALayer, let sub = l.sublayers {
                                                fillRecursively(sublayers: sub, color: color, iconID: iconID, hasFoundLayer: false)
                                            }
                                        }
                                    }
                        
                                }
                            }
                        
                            func colorThatImageWIthColor(color: UIColor, layer: CAShapeLayer) {
                                if layer.strokeColor != nil {
                                    layer.strokeColor = color.cgColor
                                }
                                if layer.fillColor != nil {
                                    layer.fillColor = color.cgColor
                                }
                            }
                        
                        }
                        

                        或查看此示例。

                        https://github.com/ravisfortune/SVGDEMO

                        【讨论】:

                          【解决方案20】:
                          let navHeight = self.navigationController?.navigationBar.frame.height;
                          let menuBtn = UIButton(type: .custom)
                          menuBtn.frame = CGRect(x: 0, y: 0, width: 45, height: navHeight!)     
                          menuBtn.setImage(UIImage(named:"image_name")!.withRenderingMode(.alwaysTemplate), for: .normal)        
                          menuBtn.tintColor = .black
                          

                          【讨论】:

                            【解决方案21】:

                            iOS 13 及以上版本,您可以简单地使用

                            let image = UIImage(named: "Heart")?.withRenderingMode(.alwaysTemplate)
                            if #available(iOS 13.0, *) {
                               imageView.image = image?.withTintColor(UIColor.white)
                            }
                            

                            【讨论】:

                              【解决方案22】:

                              斯威夫特 5

                              用背景和填充颜色重绘图像

                              extension UIImage {
                                func withBackground(color: UIColor, fill fillColor: UIColor) -> UIImage {
                                  UIGraphicsBeginImageContextWithOptions(size, true, scale)
                                  
                                  guard let ctx = UIGraphicsGetCurrentContext(), let image = cgImage else { return self }
                                  defer { UIGraphicsEndImageContext() }
                                  
                                  ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height))
                                  
                                  let rect = CGRect(origin: .zero, size: size)
                                  
                                  // draw background
                                  ctx.setFillColor(color.cgColor)
                                  ctx.fill(rect)
                                  
                                  // draw image with fill color
                                  ctx.clip(to: rect, mask: image)
                                  ctx.setFillColor(fillColor.cgColor)
                                  ctx.fill(rect)
                                  
                                  return UIGraphicsGetImageFromCurrentImageContext() ?? self
                                }
                              }
                              

                              【讨论】:

                                【解决方案23】:

                                从 iOS 13 开始就有 UIImage 的原生方法

                                let image = yourImage.withTintColor(.systemRed)
                                

                                【讨论】:

                                  【解决方案24】:

                                  另外,对于上述答案,在 iOS 13 及更高版本中有一种干净的方法

                                  let image = UIImage(named: "imageName")?.withTintColor(.white, renderingMode: .alwaysTemplate)
                                  

                                  【讨论】:

                                    【解决方案25】:

                                    这是一个适用于 Swift 5 的简单扩展:

                                    extension UIImageView {
                                    
                                    func setImageTintColor(_ color: UIColor) {
                                        let tintedImage = self.image?.withRenderingMode(.alwaysTemplate)
                                        self.image = tintedImage
                                        self.tintColor = color
                                      }
                                    }
                                    

                                    用法:

                                    myImageView.setImageTintColor(.systemBlue)
                                    

                                    【讨论】:

                                      猜你喜欢
                                      • 2015-04-10
                                      • 2017-05-23
                                      • 2023-04-03
                                      • 1970-01-01
                                      • 2020-02-26
                                      • 1970-01-01
                                      • 2014-12-20
                                      • 2014-06-17
                                      • 1970-01-01
                                      相关资源
                                      最近更新 更多