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];
相关推荐
RickeyBoy3 小时前
解决 Swift Testing 中 DI 容器的竞态条件
ios
2501_915918415 小时前
苹果App Store上架审核卡住原因分析与解决方案指南
android·ios·小程序·https·uni-app·iphone·webview
开心就好20256 小时前
不依赖 Mac 也能做 iOS 开发?跨设备开发流程
后端·ios
开心就好20257 小时前
Windows 上传 IPA 到 App Store 的步骤讲解
后端·ios
for_ever_love__8 小时前
Objective- C学习: 手动内存管理
c语言·学习·ios·objective-c
风启新尘13 小时前
ios巨魔越狱
支持向量机·ios·智能手机
Digitally13 小时前
没有充电器,如何给 iPhone 充电?
ios·iphone
bcbnb13 小时前
基于Mach-O文件的动态库与静态库归属方案及API扫描实践
后端·ios
2501_9159214314 小时前
VSCode 写 Swift 运行到 iPhone?快蝎 IDE 开发实战体验
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
spencer_tseng15 小时前
anti-screenshot (Android + iOS)
android·ios