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_9160074717 小时前
Bundle ID 注册与管理 App ID 创建指南 命名规则 权限开关与删除注意事项
android·ios·小程序·https·uni-app·iphone·webview
2501_915909061 天前
iOS 证书创建与管理 类型限制 p12 密码与云备份实操
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张1 天前
有没有更轻量的 iOS 开发环境?快蝎kxapp轻量化路径与构成
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
ii_best1 天前
iOS 投屏ios群控鹰眼中控系统安装指南|电脑端 + TestFlight + 开发者模式实操
ios·自动化·按键精灵
CHB3 天前
uni-app x 蒸汽模式 性能测试基准报告 Benchmark【Android版】
android·ios·uni-app
Magic-ZYJ3 天前
不登录、不联网也能用:我是如何设计一款“本地优先”iOS App 的
ios·app·iphone·研发·独立开发者·心情日记
_阿南_3 天前
flutter 展示的字体突然奔放了
android·flutter·ios
90后的晨仔3 天前
你的 iOS 最低部署版本即将不再被 App Store 接受
ios
2601_965798473 天前
Launch Your Wellness App Fast: The Truth About Meditation Source Code
前端·macos·ios·objective-c·cocoa
初级代码游戏4 天前
iOS开发 Swift 速记7:结构体和类
开发语言·ios·swift