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];
相关推荐
茶底世界之下19 小时前
为什么预览、录制、离线导出不能共享同一个背压策略?
ios·swift
2501_9160074720 小时前
苹果商店iOS应用上架费用全面解析:开发者计划与审核费用计算
android·ios·小程序·https·uni-app·iphone·webview
2501_9160088921 小时前
如何实现iOS App代码混淆:SwiftShield使用指南
android·ios·小程序·https·uni-app·iphone·webview
2501_915909061 天前
移动端开发工具链怎么组合比较好,iOS、Android、跨端三套配置方案
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
2501_916008891 天前
怎么用 Godot 导出 iOS 应用并上架 App Store?签名字段该填什么?
android·ios·小程序·https·uni-app·iphone·webview
2501_915918411 天前
iOS编程用什么软件好?主流工具Xcode、AppCode、CodeRunner与新兴快蝎对比
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
终端安全笔记2 天前
iOS 27 之后「策略空转」:设备升级不报错,但旧策略不再管它
android·网络·安全·ios·智能手机
9765033352 天前
iOS 上架 4.3a 被拒【uniapp专讲】
flutter·ios·objective-c·uniapp·swift
黑化旺仔2 天前
【OC】KVO
macos·ios·objective-c·cocoa
HouWan3 天前
SwiftUI 小技巧:如何读取 SwiftUI Font 的详细信息
ios·swiftui·apple