我如何从十六进制字符串格式创建一个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
}
}
其他回答
You Can Get UIColor From String Code Like
circularSpinner.fillColor = [self getUIColorObjectFromHexString:@"27b8c8" alpha:9];
//Function For Hex Color Use
- (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;
}
- (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha
{
// Convert hex string to an integer
unsigned int hexint = [self intFromHexString:hexStr];
// Create 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;
}
/Function For Hex Color Use
- (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;
}
- (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha
{
// Convert hex string to an integer
unsigned int hexint = [self intFromHexString:hexStr];
// Create 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;
}
swift 2.0+。 这段代码对我来说很好。
extension UIColor {
/// UIColor(hexString: "#cc0000")
internal convenience init?(hexString:String) {
guard hexString.characters[hexString.startIndex] == Character("#") else {
return nil
}
guard hexString.characters.count == "#000000".characters.count else {
return nil
}
let digits = hexString.substringFromIndex(hexString.startIndex.advancedBy(1))
guard Int(digits,radix:16) != nil else{
return nil
}
let red = digits.substringToIndex(digits.startIndex.advancedBy(2))
let green = digits.substringWithRange(Range<String.Index>(start: digits.startIndex.advancedBy(2),
end: digits.startIndex.advancedBy(4)))
let blue = digits.substringWithRange(Range<String.Index>(start:digits.startIndex.advancedBy(4),
end:digits.startIndex.advancedBy(6)))
let redf = CGFloat(Double(Int(red, radix:16)!) / 255.0)
let greenf = CGFloat(Double(Int(green, radix:16)!) / 255.0)
let bluef = CGFloat(Double(Int(blue, radix:16)!) / 255.0)
self.init(red: redf, green: greenf, blue: bluef, alpha: CGFloat(1.0))
}
}
此代码包括字符串格式检查。 如。
let aColor = UIColor(hexString: "#dadada")!
let failed = UIColor(hexString: "123zzzz")
据我所知,我的代码在维护可失败条件的语义和返回可选值方面没有任何缺点。这应该是最好的答案。
十六进制初始化
extension UIColor{
public convenience init(hex : String) {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
self.init(red: 1, green: 1, blue: 1, alpha: 1)
return
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
self.init(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
//Iniitailization
let myColor = UIColor(hex: "#452b4e")
编码愉快!享受! !
Swift 2.0 - Xcode 7.2
为UIColor添加扩展。
文件-新建- Swift文件-命名。添加以下内容。
extension UIColor {
convenience init(hexString:String) {
let hexString:NSString = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let scanner = NSScanner(string: hexString as String)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color:UInt32 = 0
scanner.scanHexInt(&color)
let mask = 0x000000FF
let r = Int(color >> 16) & mask
let g = Int(color >> 8) & mask
let b = Int(color) & mask
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
self.init(red:red, green:green, blue:blue, alpha:1)
}
func toHexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return NSString(format:"#%06x", rgb) as String
}
}
用法:
Ex. Setting Button's color from hexCode.
override func viewWillAppear(animated: Bool) {
loginButton.tintColor = UIColor(hexString: " hex code here ")
}
Ex. Converting Button's current color to hex Code.
override func viewWillAppear(animated: Bool) {
let hexString = loginButton.tintColor.toHexString()
print("HEX STRING: \(hexString)")
}
有一个很好的UIColor类别,其中有许多功能。
用法:
textView.textColor = [UIColor colorWithHexString:textColorHex];
NSLog(@"Text Color Hex: %@", textColorHex);
其中textColorHex有一个形式的@“FFFFFF”没有#符号。
推荐文章
- iOS如何设置应用程序图标和启动图像
- 更改UITextField和UITextView光标/插入符颜色
- 'Project Name'是通过优化编译的——步进可能会表现得很奇怪;变量可能不可用
- 如何设置回退按钮文本在Swift
- 模拟器慢动作动画现在打开了吗?
- 如何为TableView创建NSIndexPath
- 滑动删除和“更多”按钮(就像iOS 7的邮件应用程序)
- 如何比较两个nsdate:哪个是最近的?
- 使UINavigationBar透明
- 如何改变推和弹出动画在一个基于导航的应用程序
- 删除/重置核心数据中的所有条目?
- setNeedsLayout vs. setNeedsUpdateConstraints和layoutIfNeeded vs. updateConstraintsIfNeeded
- 不区分大小写的比较
- 我怎么能得到一个uiimage的高度和宽度?
- 我如何模仿地图应用程序的底部表格?