import UIKit
import Lottie
extension UIImage {
/// 【终极】Lottie JSON 文件名 → 生成 TabBar 图标(24x24,必显示)
static func fromLottie(
name: String,
size: CGSize = CGSize(width: 24, height: 24),
progress: CGFloat = 0
) -> UIImage? {
// 1. 加载 Lottie
let animation = LottieAnimation.named(name)
let animationView = LottieAnimationView(animation: animation)
// 2. 必须设置大小 + 布局
animationView.frame = CGRect(origin: .zero, size: size)
animationView.backgroundColor = .clear
animationView.contentMode = .scaleAspectFit
animationView.currentProgress = progress
// 3. 关键:临时加到 keyWindow 让它渲染(否则不显示)
if let window = UIApplication.shared.connectedScenes
.filter({ $0.activationState == .foregroundActive })
.compactMap({ $0 as? UIWindowScene })
.first?.windows.first {
window.addSubview(animationView)
animationView.layoutIfNeeded()
// 4. 渲染图片
let renderer = UIGraphicsImageRenderer(size: size)
let image = renderer.image { ctx in
animationView.drawHierarchy(in: animationView.bounds, afterScreenUpdates: true)
}
// 5. 用完移除
animationView.removeFromSuperview()
return image.withRenderingMode(.alwaysOriginal)
}
return nil
}
}