Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage animationImages tint color?

Is there a way to tint the images in an animation?

I know I can tint a single image like this:

var imageOne:UIImage = UIImage(named: "pullto_1.png")!;
    imageOne = imageOne.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
    refSequence.image = imageOne;

But when I try to do it like this it just dosen't work:

 var imageOne:UIImage = UIImage(named: "pullto_1.png")!;
    imageOne = imageOne.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)

    var image2:UIImage = UIImage(named: "pullto_2.png")!;
    image2 = image2.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)

    var image3:UIImage = UIImage(named: "pullto_3.png")!;
    image3 = image3.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)

    var image4:UIImage = UIImage(named: "pullto_4.png")!;
    image4 = image4.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)

    refSequence.animationImages = NSArray(objects: imageOne,
        image2,
        image3,
        image4

    );

    refSequence.animationDuration = 1.4;
    refSequence.animationRepeatCount = 99;
    refSequence.startAnimating();

Am I doing something wrong? Is there some way to tint the images in the animation?

Thanks

like image 719
Ferenc Avatar asked Nov 26 '14 12:11

Ferenc


1 Answers

For Swift 5: Create image with color you want with below function. Then use those images to set to your image view's animation property:

extension UIImage {    
    func imageWithColor(_ color: UIColor) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
        guard let context = UIGraphicsGetCurrentContext(), let cgImage = self.cgImage else { return nil }

        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: size.width, height: size.height)
        context.clip(to: rect, mask: cgImage)
        color.setFill()
        context.fill(rect)
        let  newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();

        return newImage
    }
}


let animImages = [
    image0.imageWithColor(color),
    image1.imageWithColor(color),
    image2.imageWithColor(color),
].compactMap({ $0 })

imageView.animationImages = animImages
imageView.animationDuration = 0.7
imageView.animationRepeatCount = 0
like image 120
huync Avatar answered Nov 15 '22 18:11

huync