2

I need to change the color of a gif programatically. The original gif is white on clear background, and I want to make it change color through code.

I've tried the answer in this thread, but that causes the gif to freeze on the first frame. Here's some of the code I'm working with.

class MyViewController: UIViewController {
    @IBOutlet weak var myImageView: UIImageView?

    override func viewDidLoad() {
        myImageView?.image = UIImage.gif(name: "my_gif")
        myImageView?.image = myImageView?.image?.maskWithColor(color: UIColor.red)
        // This creates a red, but still version of the gif
    }
}

extension UIImage {

    func maskWithColor(color: UIColor) -> UIImage? {
        let maskImage = cgImage!

        let width = size.width
        let height = size.height
        let bounds = CGRect(x: 0, y: 0, width: width, height: height)

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!

        context.clip(to: bounds, mask: maskImage)
        context.setFillColor(color.cgColor)
        context.fill(bounds)

        if let cgImage = context.makeImage() {
            let coloredImage = UIImage(cgImage: cgImage)
            return coloredImage
        } else {
            return nil
        }
    }

}

I'm currently using different gif files for each color I need as a workaround, but that sounds awfully inefficient. Any ideas?

Thanks in advance!

Community
  • 1
  • 1
Marco Cardoso
  • 150
  • 1
  • 10

1 Answers1

0

You can create a UIView and set it's background color. Then you can set the view's alpha value to 0.5 and place the view over the image view.

Like so:

let overlayView = UIView()
overlayView.frame = myImageView.frame
overlayView.backgroundColor = .red
overlayView.alpha = 0.5
view.addSubview(overlayView)

This way your not messing up the existing image view that works.

Hope this helps.

naturaln0va
  • 755
  • 6
  • 8
  • Wouldn't that create a red translucent rectangle over the gif? What I'm trying to do is change the white in the original to red, while keeping the clear background. – Marco Cardoso Jan 06 '17 at 18:09
  • Oh yeah that's exactly what that would do. Sorry about that. The reason that your posted code _freezes_ is case your setting the image of the image view to a single `UIImage`. Your code first sets the image of the image view to an animated sequence I assume then right after you set a single image for the image view. To solve this you'd need to apply the tinting code in your extension to each image in your GIF. – naturaln0va Jan 06 '17 at 18:25