//
//  UIColor.m
//  RCTBaiduMap
//
//  Created by reylen on 2025/8/19.
//  Copyright © 2025 lovebing.org. All rights reserved.
//



#import "UIColor+Hex.h"

@implementation UIColor (Hex)

+ (UIColor *)colorWithHexString:(NSString *)hexString {
    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString:@"#" 
                                                                 withString:@""] uppercaseString];
    CGFloat alpha, red, blue, green;
    
    // 处理简写格式 #RGB -> #RRGGBB
    if ([colorString length] == 3) {
        NSRange range = NSMakeRange(0, 1);
        NSString *r = [colorString substringWithRange:range];
        range.location = 1;
        NSString *g = [colorString substringWithRange:range];
        range.location = 2;
        NSString *b = [colorString substringWithRange:range];
        colorString = [NSString stringWithFormat:@"%@%@%@%@%@%@", r, r, g, g, b, b];
    }
    
    // 处理完整格式 #RRGGBB
    if ([colorString length] == 6) {
        NSRange range = NSMakeRange(0, 2);
        [[NSScanner scannerWithString:[colorString substringWithRange:range]] scanHexInt:&red];
        range.location = 2;
        [[NSScanner scannerWithString:[colorString substringWithRange:range]] scanHexInt:&green];
        range.location = 4;
        [[NSScanner scannerWithString:[colorString substringWithRange:range]] scanHexInt:&blue];
        
        return [UIColor colorWithRed:(red / 255.0f)
                              green:(green / 255.0f)
                               blue:(blue / 255.0f)
                              alpha:1.0f];
    }
    
    return nil;
}

+ (UIColor *)colorWithHex:(UInt32)hex alpha:(CGFloat)alpha {
    return [UIColor colorWithRed:((hex >> 16) & 0xFF) / 255.0f
                          green:((hex >> 8) & 0xFF) / 255.0f
                           blue:(hex & 0xFF) / 255.0f
                          alpha:alpha];
}

@end
