我如何从十六进制字符串格式创建一个UIColor,如#00FF00?
当前回答
Swift 5, iOS 14
convenience init(hex: String, alpha: CGFloat = 1.0) {
var hexFormatted: String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
if hexFormatted.hasPrefix("#") {
hexFormatted = String(hexFormatted.dropFirst())
}
assert(hexFormatted.count == 6, "Invalid hex code used.")
var rgbValue: UInt64 = 0
Scanner(string: hexFormatted).scanHexInt64(&rgbValue)
self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: alpha)
}
其他回答
有一个很好的帖子是关于如何解决OP的问题,从十六进制字符串中提取UIColor。下面给出的解决方案与其他解决方案不同,因为它支持字符串值,可能包括'0x'或'#'前缀的十六进制字符串表示…(请参阅使用)
这是主要的部分…
- (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha
{
// Convert hex string to an integer
unsigned int hexint = [self intFromHexString:hexStr];
// Create a color object, specifying alpha as well
UIColor *color =
[UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255
green:((CGFloat) ((hexint & 0xFF00) >> 8))/255
blue:((CGFloat) (hexint & 0xFF))/255
alpha:alpha];
return color;
}
助手方法……
- (unsigned int)intFromHexString:(NSString *)hexStr
{
unsigned int hexInt = 0;
// Create scanner
NSScanner *scanner = [NSScanner scannerWithString:hexStr];
// Tell scanner to skip the # character
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]];
// Scan hex value
[scanner scanHexInt:&hexInt];
return hexInt;
}
用法:
NSString *hexStr1 = @"123ABC";
NSString *hexStr2 = @"#123ABC";
NSString *hexStr3 = @"0x123ABC";
UIColor *color1 = [self getUIColorObjectFromHexString:hexStr1 alpha:.9];
NSLog(@"UIColor: %@", color1);
UIColor *color2 = [self getUIColorObjectFromHexString:hexStr2 alpha:.9];
NSLog(@"UIColor: %@", color2);
UIColor *color3 = [self getUIColorObjectFromHexString:hexStr3 alpha:.9];
NSLog(@"UIColor: %@", color3);
完整的参考文章
Swift 2 +
我已经将这个解决方案移植到Swift 2.2。注意,我已经将alpha参数更改为使用默认设置为1.0。我还根据Swift 2.2中的NSScanner类的要求将int类型更新为UInt32。
func colorWithHexString(hexString: String, alpha:CGFloat = 1.0) -> UIColor {
// Convert hex string to an integer
let hexint = Int(self.intFromHexString(hexString))
let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
// Create color object, specifying alpha as well
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
func intFromHexString(hexStr: String) -> UInt32 {
var hexInt: UInt32 = 0
// Create scanner
let scanner: NSScanner = NSScanner(string: hexStr)
// Tell scanner to skip the # character
scanner.charactersToBeSkipped = NSCharacterSet(charactersInString: "#")
// Scan hex value
scanner.scanHexInt(&hexInt)
return hexInt
}
斯威夫特 4+
采用与swift 4相同的变化逻辑,
func colorWithHexString(hexString: String, alpha:CGFloat = 1.0) -> UIColor {
// Convert hex string to an integer
let hexint = Int(self.intFromHexString(hexStr: hexString))
let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
// Create color object, specifying alpha as well
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
func intFromHexString(hexStr: String) -> UInt32 {
var hexInt: UInt32 = 0
// Create scanner
let scanner: Scanner = Scanner(string: hexStr)
// Tell scanner to skip the # character
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
// Scan hex value
scanner.scanHexInt32(&hexInt)
return hexInt
}
Swift 5 (iOS 13)+
下面显示了在SDK弃用scanHexInt32的情况下工作的更新。我将代码封装到Swift playground文件中。
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = colorWithHexString(hexString: "22F728")
view.addSubview(label)
self.view = view
}
func colorWithHexString(hexString: String, alpha:CGFloat = 1.0) -> UIColor {
// Convert hex string to an integer
let hexint = Int(self.intFromHexString(hexStr: hexString))
let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
// Create color object, specifying alpha as well
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
func intFromHexString(hexStr: String) -> UInt32 {
var hexInt: UInt32 = 0
// Create scanner
let scanner: Scanner = Scanner(string: hexStr)
// Tell scanner to skip the # character
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
// Scan hex value
hexInt = UInt32(bitPattern: scanner.scanInt32(representation: .hexadecimal) ?? 0)
return hexInt
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
彩色十六进制参考 HTML颜色名称和代码 十六进制颜色编码
Swift等价于@Tom的答案,尽管接收RGBA Int值以支持透明度:
func colorWithHex(aHex: UInt) -> UIColor
{
return UIColor(red: CGFloat((aHex & 0xFF000000) >> 24) / 255,
green: CGFloat((aHex & 0x00FF0000) >> 16) / 255,
blue: CGFloat((aHex & 0x0000FF00) >> 8) / 255,
alpha: CGFloat((aHex & 0x000000FF) >> 0) / 255)
}
//usage
var color = colorWithHex(0x7F00FFFF)
如果你想从string中使用它,你可以使用strtoul:
var hexString = "0x7F00FFFF"
let num = strtoul(hexString, nil, 16)
var colorFromString = colorWithHex(num)
下面是Swift 1.2版本,作为UIColor的扩展。这允许你这样做
let redColor = UIColor(hex: "#FF0000")
我觉得这是最自然的做法。
extension UIColor {
// Initialiser for strings of format '#_RED_GREEN_BLUE_'
convenience init(hex: String) {
let redRange = Range<String.Index>(start: hex.startIndex.advancedBy(1), end: hex.startIndex.advancedBy(3))
let greenRange = Range<String.Index>(start: hex.startIndex.advancedBy(3), end: hex.startIndex.advancedBy(5))
let blueRange = Range<String.Index>(start: hex.startIndex.advancedBy(5), end: hex.startIndex.advancedBy(7))
var red : UInt32 = 0
var green : UInt32 = 0
var blue : UInt32 = 0
NSScanner(string: hex.substringWithRange(redRange)).scanHexInt(&red)
NSScanner(string: hex.substringWithRange(greenRange)).scanHexInt(&green)
NSScanner(string: hex.substringWithRange(blueRange)).scanHexInt(&blue)
self.init(
red: CGFloat(red) / 255,
green: CGFloat(green) / 255,
blue: CGFloat(blue) / 255,
alpha: 1
)
}
}
斯威夫特版本:
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
}
}
上面的几个解决方案涉及到一些不必要的nsstring使用。这个UIColor类扩展更简单更快:
+ colorWithHex:(UInt32)hex alpha:(CGFloat)alpha
{
return [UIColor colorWithRed:((hex & 0xFF0000) >> 16)/255.0
green:((hex & 0x00FF00) >> 8)/255.0
blue:( hex & 0x0000FF)/255.0
alpha:alpha];
}
简单来说:
return [UIColor colorWithHex:0x006400 alpha:1.0]; // HTML darkgreen
推荐文章
- iOS如何设置应用程序图标和启动图像
- 更改UITextField和UITextView光标/插入符颜色
- 'Project Name'是通过优化编译的——步进可能会表现得很奇怪;变量可能不可用
- 如何设置回退按钮文本在Swift
- 模拟器慢动作动画现在打开了吗?
- 如何为TableView创建NSIndexPath
- 滑动删除和“更多”按钮(就像iOS 7的邮件应用程序)
- 如何比较两个nsdate:哪个是最近的?
- 使UINavigationBar透明
- 如何改变推和弹出动画在一个基于导航的应用程序
- 删除/重置核心数据中的所有条目?
- setNeedsLayout vs. setNeedsUpdateConstraints和layoutIfNeeded vs. updateConstraintsIfNeeded
- 不区分大小写的比较
- 我怎么能得到一个uiimage的高度和宽度?
- 我如何模仿地图应用程序的底部表格?