Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tint an animated UIImageView?

I'm attempting to apply tint of a UIImageView consisting of programatically loaded animationImages. Currently using iOS 9.3.

I think I've tried every proposed solution found here for applying the tint including:

  • Setting the .renderMode on load with: let newImage: UIImage? = UIImage(named: filename as String)!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
  • Setting the tintView either in the Storyboard or programatically with: zeroImageView.tintColor = UIColor.redColor()
  • Setting the image .renderMode through the UIImageView itself: zeroImageView.image = zeroImageView.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
  • Setting the UIImageView's renderMode through the Interface Builder user defined runtime attributes: imageRenderingMode Number 2

The image sequence is of PNGs with transparency, so, I would like to re-colour the image and maintain the transparency.

I've had no luck and am sort of at a loss. Wondering if maybe these methods only work for a still UIAnimationView? Any help would be greatly appreciated, thanks!

Here's some code:

// Load all images
    while let element = enumerator.nextObject() as? String {
        if element.hasSuffix("png") {
            let filename: NSString = "Digits/0/" + element
            print(filename)
            imageNames.append(filename as String)
            let newImage: UIImage? = UIImage(named: filename as String)!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
            images.append(newImage!)
            zeroImageView.tintColor = UIColor.redColor()

        }
    }

// Make animated UIImageView
    zeroImageView.userInteractionEnabled = false
    zeroImageView.animationImages = images
    zeroImageView.animationDuration = 2.0
    zeroImageView.startAnimating()
    zeroImageView.tintColor = UIColor.redColor()
like image 845
E.R. Avatar asked Sep 06 '25 08:09

E.R.


1 Answers

Try this...

extension UIImage {
    func image(withTint tint: UIColor) -> UIImage? {
        guard let cgImage = cgImage else {
            return nil
        }

        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }

        let rect = CGRect(origin: .zero, size: size)

        context.translateBy(x: 0, y: size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.setBlendMode(.normal)
        context.clip(to: rect, mask: cgImage)
        tint.setFill()
        context.fill(rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}
like image 180
Alexander Smith Avatar answered Sep 09 '25 04:09

Alexander Smith