title: Swift - How to change a png tint color without losing the clear background?
body: <p>I've tried the following code and it works. It adds a tint color to my png image but the clear background turns black. The image has details like a shadow or so, so I don't use the normal renderImageAsTemplate property.</p>
  
  <pre><code>extension UIImage {
      public func tintImage(with fillColor: UIColor) -&gt; 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 (losing 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(.normal)
              context.draw(context.makeImage()!, in: rect)
          }
      }
  
      fileprivate func modifiedImage(_ draw: (CGContext, CGRect) -&gt; ()) -&gt; 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!
      }
  }
  </code></pre>
  
  <p>Is there a way to change the image tint color while maintaining the clear background of the PNG? </p>