UIImage animationImages tint color?

前端 未结 6 1743
醉话见心
醉话见心 2020-12-31 13:58

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\"         


        
6条回答
  •  孤城傲影
    2020-12-31 14:30

    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
    

提交回复
热议问题