我如何从十六进制字符串格式创建一个UIColor,如#00FF00?
当前回答
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
- (UIColor*)colorWithHexString:(NSString*)hex
{
NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) return [UIColor grayColor];
// strip 0X if it appears
if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
if ([cString length] != 6) return [UIColor grayColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f)
green:((float) g / 255.0f)
blue:((float) b / 255.0f)
alpha:1.0f];
}
抛光扩展从原来的答案@Tom 请随意在这里更新代码
extension UIColor{
convenience init (hexString:String) {
var cleanString:String = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cleanString.hasPrefix("#")) {
cleanString = cleanString.substringFromIndex(cleanString.startIndex.advancedBy(1))
}
if (cleanString.characters.count != 6) {
self.init()
}
else{
var rgbValue = UInt32()
let scanner = NSScanner(string: cleanString)
scanner.scanHexInt(&rgbValue)
self.init(
red: CGFloat((rgbValue & 0xFF0000) >> 16)/255.0,
green: CGFloat((rgbValue & 0xFF00) >> 8)/255.0,
blue: CGFloat(rgbValue & 0xFF)/255.0,
alpha: 1.0)
}
}
}
我找到了一个很好的UIColor类别,UIColor+PXExtensions。
用法:UIColor *mycolor = [UIColor pxColorWithHexValue:@"#BADA55"];
而且,为了防止链接到我的要点失败,这里是实际的实现代码:
//
// UIColor+PXExtensions.m
//
#import "UIColor+UIColor_PXExtensions.h"
@implementation UIColor (UIColor_PXExtensions)
+ (UIColor*)pxColorWithHexValue:(NSString*)hexValue
{
//Default
UIColor *defaultResult = [UIColor blackColor];
//Strip prefixed # hash
if ([hexValue hasPrefix:@"#"] && [hexValue length] > 1) {
hexValue = [hexValue substringFromIndex:1];
}
//Determine if 3 or 6 digits
NSUInteger componentLength = 0;
if ([hexValue length] == 3)
{
componentLength = 1;
}
else if ([hexValue length] == 6)
{
componentLength = 2;
}
else
{
return defaultResult;
}
BOOL isValid = YES;
CGFloat components[3];
//Seperate the R,G,B values
for (NSUInteger i = 0; i < 3; i++) {
NSString *component = [hexValue substringWithRange:NSMakeRange(componentLength * i, componentLength)];
if (componentLength == 1) {
component = [component stringByAppendingString:component];
}
NSScanner *scanner = [NSScanner scannerWithString:component];
unsigned int value;
isValid &= [scanner scanHexInt:&value];
components[i] = (CGFloat)value / 256.0f;
}
if (!isValid) {
return defaultResult;
}
return [UIColor colorWithRed:components[0]
green:components[1]
blue:components[2]
alpha:1.0];
}
@end
为UIColor创建优雅的扩展:
extension UIColor {
convenience init(string: String) {
var uppercasedString = string.uppercased()
uppercasedString.remove(at: string.startIndex)
var rgbValue: UInt32 = 0
Scanner(string: uppercasedString).scanHexInt32(&rgbValue)
let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
let blue = CGFloat(rgbValue & 0x0000FF) / 255.0
self.init(red: red, green: green, blue: blue, alpha: 1)
}
}
创建红色:
let red = UIColor(string: "#ff0000")
extension UIColor {
convenience init(hexaString: String, alpha: CGFloat = 1) {
let chars = Array(hexaString.dropFirst())
self.init(red: .init(strtoul(String(chars[0...1]),nil,16))/255,
green: .init(strtoul(String(chars[2...3]),nil,16))/255,
blue: .init(strtoul(String(chars[4...5]),nil,16))/255,
alpha: alpha)}
}
用法:
let redColor = UIColor(hexaString: "#FF0000") // r 1,0 g 0,0 b 0,0 a 1,0
let transparentRed = UIColor(hexaString: "#FF0000", alpha: 0.5) // r 1,0 g 0,0 b 0,0 a 0,5
另一种选择是将六值转换为无符号整数,并从中提取相应的值:
extension UIColor {
convenience init(hexaString: String, alpha: CGFloat = 1) {
self.init(hexa: UInt(hexaString.dropFirst(), radix: 16) ?? 0, alpha: alpha)
}
convenience init(hexa: UInt, alpha: CGFloat = 1) {
self.init(red: .init((hexa & 0xff0000) >> 16) / 255,
green: .init((hexa & 0xff00 ) >> 8) / 255,
blue: .init( hexa & 0xff ) / 255,
alpha: alpha)
}
}
let purpleColor = UIColor(hexaString: "#FF00FF") // r 1,0 g 0,0 b 1,0 a 1,0
let transparentYellow = UIColor(hexaString: "#FFFF00", alpha: 0.5) // r 1,0 g 1,0 b 0,0 a 0,5
推荐文章
- iOS如何设置应用程序图标和启动图像
- 更改UITextField和UITextView光标/插入符颜色
- 'Project Name'是通过优化编译的——步进可能会表现得很奇怪;变量可能不可用
- 如何设置回退按钮文本在Swift
- 模拟器慢动作动画现在打开了吗?
- 如何为TableView创建NSIndexPath
- 滑动删除和“更多”按钮(就像iOS 7的邮件应用程序)
- 如何比较两个nsdate:哪个是最近的?
- 使UINavigationBar透明
- 如何改变推和弹出动画在一个基于导航的应用程序
- 删除/重置核心数据中的所有条目?
- setNeedsLayout vs. setNeedsUpdateConstraints和layoutIfNeeded vs. updateConstraintsIfNeeded
- 不区分大小写的比较
- 我怎么能得到一个uiimage的高度和宽度?
- 我如何模仿地图应用程序的底部表格?