我如何从十六进制字符串格式创建一个UIColor,如#00FF00?
当前回答
斯威夫特版本:
extension UIColor {
convenience init?(var hex: String) {
hex = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
hex = (hex.hasPrefix("#")) ? hex.substringFromIndex(advance(hex.startIndex, 1)) : hex
var value: UInt32 = 0
if NSScanner(string: hex).scanHexInt(&value) {
if count(hex) == 8 {
self.init(red: CGFloat((value & 0xFF000000) >> 24) / 255.0,
green: CGFloat((value & 0x00FF0000) >> 16) / 255.0,
blue: CGFloat((value & 0x0000FF00) >> 8) / 255.0,
alpha: CGFloat((value & 0x000000FF)) / 255.0)
return
} else if count(hex) == 6 {
self.init(red: CGFloat((value & 0xFF0000) >> 16) / 255.0,
green: CGFloat((value & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(value & 0x0000FF) / 255.0,
alpha: 1.0)
return
}
}
self.init()
return nil
}
}
其他回答
据我所知,没有从十六进制字符串到UIColor(或CGColor)的内置转换。但是,您可以很容易地为此目的编写几个函数—例如,参见iphone开发访问uicolor组件
我发现最简单的方法是使用宏。只要把它包括在你的标题中,它就可以在你的整个项目中使用。
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
Uicolor宏十六进制值
这段代码的格式化版本:
#define UIColorFromRGB(rgbValue) \
[UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0x00FF00) >> 8))/255.0 \
blue:((float)((rgbValue & 0x0000FF) >> 0))/255.0 \
alpha:1.0]
用法:
label.textColor = UIColorFromRGB(0xBC1128);
迅速:
static func UIColorFromRGB(_ rgbValue: Int) -> UIColor! {
return UIColor(
red: CGFloat((Float((rgbValue & 0xff0000) >> 16)) / 255.0),
green: CGFloat((Float((rgbValue & 0x00ff00) >> 8)) / 255.0),
blue: CGFloat((Float((rgbValue & 0x0000ff) >> 0)) / 255.0),
alpha: 1.0)
}
这是一个接受十六进制字符串并返回UIColor的函数。 (你可以输入十六进制字符串格式:#ffffff或ffffff)
用法:
var color1 = hexStringToUIColor("#d3d3d3")
斯威夫特4:
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
斯威夫特3:
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.characters.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
斯威夫特2:
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString
if (cString.hasPrefix("#")) {
cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))
}
if ((cString.characters.count) != 6) {
return UIColor.grayColor()
}
var rgbValue:UInt32 = 0
NSScanner(string: cString).scanHexInt(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
沙德源代码:/ gist: de147c42d7b3063ef7bc
我已经找到了一个与Android使用的十六进制格式字符串100%兼容的解决方案,我发现这在进行跨平台移动开发时非常有用。它让我在两个平台上都使用一种颜色。您可以在没有归属的情况下随意重用,如果您愿意,也可以在Apache许可下重用。
#import "UIColor+HexString.h"
@interface UIColor(HexString)
+ (UIColor *) colorWithHexString: (NSString *) hexString;
+ (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length;
@end
@implementation UIColor(HexString)
+ (UIColor *) colorWithHexString: (NSString *) hexString {
NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];
CGFloat alpha, red, blue, green;
switch ([colorString length]) {
case 3: // #RGB
alpha = 1.0f;
red = [self colorComponentFrom: colorString start: 0 length: 1];
green = [self colorComponentFrom: colorString start: 1 length: 1];
blue = [self colorComponentFrom: colorString start: 2 length: 1];
break;
case 4: // #ARGB
alpha = [self colorComponentFrom: colorString start: 0 length: 1];
red = [self colorComponentFrom: colorString start: 1 length: 1];
green = [self colorComponentFrom: colorString start: 2 length: 1];
blue = [self colorComponentFrom: colorString start: 3 length: 1];
break;
case 6: // #RRGGBB
alpha = 1.0f;
red = [self colorComponentFrom: colorString start: 0 length: 2];
green = [self colorComponentFrom: colorString start: 2 length: 2];
blue = [self colorComponentFrom: colorString start: 4 length: 2];
break;
case 8: // #AARRGGBB
alpha = [self colorComponentFrom: colorString start: 0 length: 2];
red = [self colorComponentFrom: colorString start: 2 length: 2];
green = [self colorComponentFrom: colorString start: 4 length: 2];
blue = [self colorComponentFrom: colorString start: 6 length: 2];
break;
default:
[NSException raise:@"Invalid color value" format: @"Color value %@ is invalid. It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", hexString];
break;
}
return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];
}
+ (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {
NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
unsigned hexComponent;
[[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
return hexComponent / 255.0;
}
@end
迅速:
extension UIColor {
convenience init?(hexString: String?) {
let input: String! = (hexString ?? "")
.replacingOccurrences(of: "#", with: "")
.uppercased()
var alpha: CGFloat = 1.0
var red: CGFloat = 0
var blue: CGFloat = 0
var green: CGFloat = 0
switch (input.count) {
case 3 /* #RGB */:
red = Self.colorComponent(from: input, start: 0, length: 1)
green = Self.colorComponent(from: input, start: 1, length: 1)
blue = Self.colorComponent(from: input, start: 2, length: 1)
break
case 4 /* #ARGB */:
alpha = Self.colorComponent(from: input, start: 0, length: 1)
red = Self.colorComponent(from: input, start: 1, length: 1)
green = Self.colorComponent(from: input, start: 2, length: 1)
blue = Self.colorComponent(from: input, start: 3, length: 1)
break
case 6 /* #RRGGBB */:
red = Self.colorComponent(from: input, start: 0, length: 2)
green = Self.colorComponent(from: input, start: 2, length: 2)
blue = Self.colorComponent(from: input, start: 4, length: 2)
break
case 8 /* #AARRGGBB */:
alpha = Self.colorComponent(from: input, start: 0, length: 2)
red = Self.colorComponent(from: input, start: 2, length: 2)
green = Self.colorComponent(from: input, start: 4, length: 2)
blue = Self.colorComponent(from: input, start: 6, length: 2)
break
default:
NSException.raise(NSExceptionName("Invalid color value"), format: "Color value \"%@\" is invalid. It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", arguments:getVaList([hexString ?? ""]))
}
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
static func colorComponent(from string: String!, start: Int, length: Int) -> CGFloat {
let substring = (string as NSString)
.substring(with: NSRange(location: start, length: length))
let fullHex = length == 2 ? substring : "\(substring)\(substring)"
var hexComponent: UInt64 = 0
Scanner(string: fullHex)
.scanHexInt64(&hexComponent)
return CGFloat(Double(hexComponent) / 255.0)
}
}
大多数发布的解决方案使用了Scanner,但至少在现代Swift中你并不真正需要它。相反,你可以简单地使用UInt init和基数16,然后使用基本的二进制操作来获得UIColor组件:
func stringToColor(color: String) -> UIColor {
guard let i = UInt(color, radix: 16) else {
return UIColor.white
}
return UIColor(
red: CGFloat((i & 0xFF0000) >> 16) / 255.0,
green: CGFloat((i & 0xFF00) >> 8) / 255.0,
blue: CGFloat(i & 0xFF) / 255.0,
alpha: 1.0
)
}
这个解决方案期望输入像“FF00FF”,你可能需要删除前面的哈希符号(#),如果你的字符串中有一个。
推荐文章
- 是否可以为iPhone应用程序(如YouTube和地图)注册一个基于http+域的URL方案?
- 模拟器错误fbssystemservicdomain代码4
- 改变UISegmentedControl的字体大小
- 我可以强制UITableView隐藏分隔符之间的空单元格吗?
- 获取用户当前位置/坐标
- 获得推送通知,而应用程序在前台iOS
- 如何取消选定的UITableView单元格?
- 设置自定义UITableViewCells的高度
- 在SwiftUI中创建一个VStack填充屏幕宽度
- 移动文本字段时,键盘出现迅速
- 让iPhone震动
- 将NSString转换为NSDate(然后再转换回来)
- 如何在swift中逆向循环迭代?
- applicationwillenter前台vs. applicationDidBecomeActive, applicationWillResignActive vs. applicationDidEnterBackground
- 如何在扑动中格式化日期时间