一、先了解什么是Hex色值
简单来说就是用十六机制来表示三原色,三原色不同强度组合出不同颜色;
详见:Hex色值是什么(含透明度)文章来源:https://www.toymoban.com/news/detail-859997.html
二、代码实现
iOS不如 Kotlin 有API可直接支持HEX赋值,得自己写个扩展方法文章来源地址https://www.toymoban.com/news/detail-859997.html
普通无透明度代码如下:
// 示例
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):
// 示例
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];
到了这里,关于iOS 使用Hex色值设置颜色(可设置透明度使用4个字节色值赋值)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!