iOS 使用Hex色值设置颜色(可设置透明度使用4个字节色值赋值)

一、先了解什么是Hex色值

简单来说就是用十六机制来表示三原色,三原色不同强度组合出不同颜色;

详见:Hex色值是什么(含透明度)

二、代码实现

iOS不如 Kotlin 有API可直接支持HEX赋值,得自己写个扩展方法

普通无透明度代码如下:

cpp 复制代码
    // 示例
    NSString *hexStr = @"#FFFFFF";
    if ([hexStr hasPrefix:@"#"]) {
         hexStr = [cString substringFromIndex:1];
    }
    // 解析RGB值
    NSUInteger red = 0, green = 0, blue = 0;
    [[NSScanner scannerWithString:cString] scanHexInt:&red];
    [[NSScanner scannerWithString:[cString substringWithRange:NSMakeRange(2, 2)]] scanHexInt:&green];
    [[NSScanner scannerWithString:[cString substringWithRange:NSMakeRange(4, 2)]] scanHexInt:&blue];

    // 将RGB值转换为CGFloat并创建UIColor
    CGFloat redFloat = (CGFloat)red / 255.0;
    CGFloat greenFloat = (CGFloat)green / 255.0;
    CGFloat blueFloat = (CGFloat)blue / 255.0;

    return [UIColor colorWithRed:redFloat green:greenFloat blue:blueFloat alpha:1.0];

带透明度的代码如下(注意此处解析顺序是RGBA,如仿Kotlin可改为ARGB):

cpp 复制代码
    // 示例
    NSString *hexStr = @"#FFFFFFFF";
    if ([hexStr hasPrefix:@"#"]) {
         hexStr = [cString substringFromIndex:1];
    }
    // 解析RGBA值
    NSUInteger red = 0, green = 0, blue = 0, alpha = 0;
    [[NSScanner scannerWithString:cString] scanHexInt:&red];
    [[NSScanner scannerWithString:[cString substringWithRange:NSMakeRange(2, 2)]] scanHexInt:&green];
    [[NSScanner scannerWithString:[cString substringWithRange:NSMakeRange(4, 2)]] scanHexInt:&blue];
    [[NSScanner scannerWithString:[cString substringWithRange:NSMakeRange(6, 2)]] scanHexInt:&alpha];

    // 将RGBA值转换为CGFloat并创建UIColor
    CGFloat redFloat = (CGFloat)red / 255.0;
    CGFloat greenFloat = (CGFloat)green / 255.0;
    CGFloat blueFloat = (CGFloat)blue / 255.0;
    CGFloat alphaFloat = (CGFloat)alpha / 255.0;

    return [UIColor colorWithRed:redFloat green:greenFloat blue:blueFloat alpha:alphaFloat];
相关推荐
2501_916008891 天前
iOS开发APP上架全流程解析:从开发到App Store的完整指南
android·ios·小程序·https·uni-app·iphone·webview
2501_915909062 天前
Charles 抓不到包怎么办?iOS 调试过程中如何判断请求路径
android·ios·小程序·https·uni-app·iphone·webview
2501_916007472 天前
iOS和iPadOS文件管理系统全面解析与使用指南
android·ios·小程序·https·uni-app·iphone·webview
2501_915921432 天前
iOS App 开发阶段性能优化,观察 CPU、内存和日志变化
android·ios·性能优化·小程序·uni-app·iphone·webview
游戏开发爱好者82 天前
在 iOS 开发、测试与上架过程中 如何做证书管理
android·ios·小程序·https·uni-app·iphone·webview
ii_best2 天前
按键精灵安卓/IOS手机助手 × 手机按键 App:1 分钟搞定设备连接(超详细教程)
android·ios·智能手机·自动化·编辑器
2501_916007472 天前
在没有 Mac 的情况下完成 iOS 应用上架 App Store
android·macos·ios·小程序·uni-app·iphone·webview
TheNextByte12 天前
iPhone存储空间已满?如何轻松释放iPhone空间?
android·ios·iphone
—Qeyser3 天前
Flutter 颜色完全指南
android·flutter·ios
2501_916008893 天前
iOS 上架需要哪些准备,账号、Bundle ID、证书、描述文件、安装测试及上传
android·ios·小程序·https·uni-app·iphone·webview