//
//  UIImage+Ex.swift
//  KittensTravelNotes
//
//  Created by 100Years on 2025/7/6.
//

public extension UIImage {
    // 压缩图片到指定尺寸
    func compressImageSize(to size: CGSize) -> UIImage {
        let targetSize = size
        if self.size.width > targetSize.width || self.size.height > targetSize.height {
            return kf.resize(to: targetSize)
        }
        return self
    }
    
    
    public var pngImage:UIImage?{
        // 将 UIImage 转为 PNG Data
        guard let pngData = self.pngData() else {
            print("Failed to convert WebP image to PNG data.")
            return nil
        }
        
        // 使用 PNG Data 创建新的 UIImage
        return UIImage(data: pngData)
    }
    
    /// 将颜色转换为 UIImage
    /// - Parameters:
    ///   - color: 目标颜色
    ///   - size: 图片尺寸（默认 1x1）
    /// - Returns: 转换后的 UIImage
    public static func colorFrom(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage? {
        // 创建一个矩形
        let rect = CGRect(origin: .zero, size: size)
        
        // 开始图形上下文
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        
        // 设置颜色填充
        color.setFill()
        UIRectFill(rect)
        
        // 获取生成的图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        // 结束图形上下文
        UIGraphicsEndImageContext()
        
        return image
    }
}

