// // ViewController.swift // Render // // Created by ForC on 2021/7/1. // import UIKit class ViewController: UIViewController { let imageV = UIImageView() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.gray let image = UIImage(named: "grassAddGood")!.withRenderingMode(.alwaysTemplate) /// fail let image1 = UIImage(named: "grassAddGood")! ///success let image2 = render(UIImage(named: "grassAddGood")!, .green) ///success imageV.image = image imageV.tintColor = .red imageV.frame = CGRect(x: 100, y: 100, width: 100, height: 100) view.addSubview(imageV) DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.start() DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.end() } } } func start() { if imageV.layer.animation(forKey: "totationAnimation") == nil { let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.duration = 0.5; animation.repeatCount = MAXFLOAT; animation.toValue = .pi * 2.0 imageV.layer.add(animation, forKey: "rotationAnimation") } imageV.layer.speed = 1 } func end() { guard imageV.layer.speed > 0 else { return } imageV.layer.speed = 0 imageV.layer.timeOffset = 0 } func render(_ image: UIImage, _ tintColor: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale); let context = UIGraphicsGetCurrentContext() context!.translateBy(x: 0, y: image.size.height) context!.scaleBy(x: 1.0, y: -1.0) context!.setBlendMode(.normal) context!.clip(to: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), mask: image.cgImage!) tintColor.setFill() context?.fill(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage! } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { /// fail /// If an animation is used -withRenderingMode and an image is used after the animation is complete, the view transition will fail /// any viewcontroller present(Test2ViewController(), animated: true) { /// dont perform print("hq111") } } }