//
//  UIImage+XXGImage.m
//  XXGPlayKit
//
//  Created by apple on 2025/3/10.
//

#import "UIImage+XXGImage.h"
#import "NSData+SunHope.h"
#import "NSString+XXGString.h"
#import "XXGLocaleString.h"

@implementation UIImage (XXGImage)

+ (UIImage *)xxpk_imageWithColor:(UIColor *)color {
    
    CGRect rect=CGRectMake(0.0f,0.0f, 1.0f,1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

+ (UIImage *)xxpk_imageBundleOfName:(NSString *)imageName {
    
    if (!imageName) {
        return nil;
    }
    
    UIImage *image = nil;
    
    NSString *imgPath= [[XXGLocaleString getBundle] stringByAppendingPathComponent:imageName];
    
    if (imgPath.xxpk_isNotEmpty) {
        
        image = [UIImage imageWithContentsOfFile:imgPath];
    }
    
    if (!image) {
        // 线上环境加载加密后的图片
        NSData *encryptedData = [NSData dataWithContentsOfFile:imgPath];
       
       // 解密图片数据
        image = [encryptedData xxpk_decryptImageWithRandomFactor];
    }
    
    return image;
}

- (UIImage *)xxpk_imageWithTintColor:(UIColor *)tintColor {
   
    if (!tintColor) return self;
    
    // 保持图片比例和缩放因子
    UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat defaultFormat];
    format.scale = self.scale;
    format.opaque = NO;
    
    UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:self.size format:format];
    
    return [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull context) {
        // 应用目标颜色
        [tintColor setFill];
        
        // 绘制路径（确保覆盖所有非透明区域）
        CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
        [self drawInRect:bounds];
        
        // 使用混合模式覆盖颜色
        CGContextSetBlendMode(context.CGContext, kCGBlendModeSourceIn);
        CGContextFillRect(context.CGContext, bounds);
    }];
}
@end
