我如何从十六进制字符串创建一个UIColor ?

我如何从十六进制字符串格式创建UIColor,如#00FF00?

317496 次浏览

据我所知,没有从十六进制字符串到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]

uicolol宏十六进制值

这段代码的格式化版本:

#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)
}

我已经找到了一个与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)
}
}

这是另一种选择。

- (UIColor *)colorWithRGBHex:(UInt32)hex
{
int r = (hex >> 16) & 0xFF;
int g = (hex >> 8) & 0xFF;
int b = (hex) & 0xFF;


return [UIColor colorWithRed:r / 255.0f
green:g / 255.0f
blue:b / 255.0f
alpha:1.0f];
}

是一个很好的UIColor类别,其中有许多功能。

用法:

textView.textColor = [UIColor colorWithHexString:textColorHex];
NSLog(@"Text Color Hex: %@", textColorHex);

其中textColorHex有一个形式的@“FFFFFF”没有#符号。

一个简明的解决方案:

// Assumes input like "#00FF00" (#RRGGBB).
+ (UIColor *)colorFromHexString:(NSString *)hexString {
unsigned rgbValue = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexString];
[scanner setScanLocation:1]; // bypass '#' character
[scanner scanHexInt:&rgbValue];
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}

我找到了一个很好的UIColor类别,< >强用户界面颜色+ PXExtensions < / >强

用法:# EYZ0

而且,为了防止链接到我的要点失败,这里是实际的实现代码:

//
//  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

另一个带有alpha的版本

#define UIColorFromRGBA(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF000000) >> 24))/255.0 green:((float)((rgbValue & 0xFF0000) >> 16))/255.0 blue:((float)((rgbValue & 0xFF00) >> 8 ))/255.0 alpha:((float)((rgbValue & 0xFF))/255.0)]

另一个实现允许字符串像"FFF""FFFFFF",并使用alpha:

+ (UIColor *) colorFromHexString:(NSString *)hexString alpha: (CGFloat)alpha{
NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
if([cleanString length] == 3) {
cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@",
[cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
[cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
[cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
}
if([cleanString length] == 6) {
cleanString = [cleanString stringByAppendingString:@"ff"];
}


unsigned int baseValue;
[[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];


float red = ((baseValue >> 24) & 0xFF)/255.0f;
float green = ((baseValue >> 16) & 0xFF)/255.0f;
float blue = ((baseValue >> 8) & 0xFF)/255.0f;


return [UIColor colorWithRed:red green:green blue:blue 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);

完整参考文章

斯威夫特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颜色名称和代码

颜色十六进制颜色代码

您可以使用各种在线工具将HEX字符串转换为实际的UIColor。查看uicolor.orgUI颜色选择器。输出将被转换为Objective-C代码,如下所示:

[UIColor colorWithRed:0.93 green:0.80 blue:0.80 alpha:1.0];

可以嵌入到应用程序中。希望这能有所帮助!

有了cocoapod支持,这很好

https://github.com/mRs-/HexColors < a href = " https://github.com/mRs-/HexColors " > < / >

// with hash
NSColor *colorWithHex = [NSColor colorWithHexString:@"#ff8942" alpha:1];


// wihtout hash
NSColor *secondColorWithHex = [NSColor colorWithHexString:@"ff8942" alpha:1];


// short handling
NSColor *shortColorWithHex = [NSColor colorWithHexString:@"fff" alpha:1]

我最终为UIColor创建了一个类别,我可以在我的其他项目中重用,并添加了这个函数:

+ (UIColor *)colorFromHex:(unsigned long)hex
{
return [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16))/255.0
green:((float)((hex & 0xFF00) >> 8))/255.0
blue:((float)(hex & 0xFF))/255.0
alpha:1.0];
}

用法是这样的:

UIColor *customRedColor = [UIColor colorFromHex:0x990000];

这比传递字符串并将其转换为数字然后移位位要快得多。

你也可以从你的.pch文件中导入类别,这样你就可以很容易地在你的应用程序中到处使用colorFromHex,就像它内置到UIColor一样:

#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
// Your other stuff here...
#import "UIColor+HexColor.h"
#endif
 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;
}

上面的几个解决方案涉及到一些不必要的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

使用这个类别:

在文件用户界面颜色+ Hexadecimal.h

#import <UIKit/UIKit.h>


@interface UIColor(Hexadecimal)


+ (UIColor *)colorWithHexString:(NSString *)hexString;


@end

在文件用户界面颜色+ Hexadecimal.m

#import "UIColor+Hexadecimal.h"


@implementation UIColor(Hexadecimal)


+ (UIColor *)colorWithHexString:(NSString *)hexString {
unsigned rgbValue = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexString];
[scanner setScanLocation:1]; // bypass '#' character
[scanner scanHexInt:&rgbValue];


return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}


@end

你想在课堂上使用它:

#import "UIColor+Hexadecimal.h"

和:

[UIColor colorWithHexString:@"#6e4b4b"];
< p > # EYZ0 < br > (你可以输入十六进制字符串格式:#ffffffffffff)

用法:

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)
)
}

< br >


来源:# EYZ0

一个伟大的Swift实现(为Xcode 7更新)使用扩展,从各种不同的答案和地方拉到一起。在结尾还需要字符串扩展名。

使用:

let hexColor = UIColor(hex: "#00FF00")

注意:我添加了一个选项,为alpha通道的标准6位十六进制值的末尾添加了2个额外的数字(传入值为00-99)。如果这冒犯了你,就把它拿掉。您可以实现它来传递一个可选的alpha参数。

扩展:

extension UIColor {


convenience init(var hex: String) {
var alpha: Float = 100
let hexLength = hex.characters.count
if !(hexLength == 7 || hexLength == 9) {
// A hex must be either 7 or 9 characters (#RRGGBBAA)
print("improper call to 'colorFromHex', hex length must be 7 or 9 chars (#GGRRBBAA)")
self.init(white: 0, alpha: 1)
return
}


if hexLength == 9 {
// Note: this uses String subscripts as given below
alpha = hex[7...8].floatValue
hex = hex[0...6]
}


// Establishing the rgb color
var rgb: UInt32 = 0
let s: NSScanner = NSScanner(string: hex)
// Setting the scan location to ignore the leading `#`
s.scanLocation = 1
// Scanning the int into the rgb colors
s.scanHexInt(&rgb)


// Creating the UIColor from hex int
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: CGFloat(alpha / 100)
)
}
}
< p >字符串扩展:
# EYZ0
# EYZ0 < / p >
extension String {


/**
Returns the float value of a string
*/
var floatValue: Float {
return (self as NSString).floatValue
}


/**
Subscript to allow for quick String substrings ["Hello"][0...1] = "He"
*/
subscript (r: Range<Int>) -> String {
get {
let start = self.startIndex.advancedBy(r.startIndex)
let end = self.startIndex.advancedBy(r.endIndex - 1)
return self.substringWithRange(start..<end)
}
}
}

swift 1.2更新

class func colorWithHexString (hex:String) -> UIColor {
var cString: NSString = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString


if (cString.hasPrefix("#")) {
cString = cString.substringFromIndex(1)
}


if (count(cString as String) != 6) {
return UIColor.grayColor()
}


var rString: String = cString.substringToIndex(2)
var gString: String = (cString.substringFromIndex(2) as NSString).substringToIndex(2)
var bString: String = (cString.substringFromIndex(4) as NSString).substringToIndex(2)


var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(Float(r) / 255.0), green: CGFloat(Float(g) / 255.0), blue: CGFloat(Float(b) / 255.0), alpha: CGFloat(1))


}

除了颜色,我还喜欢保证alpha,所以我自己写类别

+ (UIColor *) colorWithHex:(int)color {


float red = (color & 0xff000000) >> 24;
float green = (color & 0x00ff0000) >> 16;
float blue = (color & 0x0000ff00) >> 8;
float alpha = (color & 0x000000ff);


return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha/255.0];
}

像这样很容易使用

[UIColor colorWithHex:0xFF0000FF]; //Red
[UIColor colorWithHex:0x00FF00FF]; //Green
[UIColor colorWithHex:0x00FF00FF]; //Blue
[UIColor colorWithHex:0x0000007F]; //transparent black

斯威夫特版本:

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
}
}

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)

此代码将从十六进制颜色字符串中返回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];
}

你可以做这样的扩展

extension UIColor {
convenience init(hex: UInt, alpha: CGFloat = 1) {
self.init(
red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hex & 0x0000FF) / 255.0,
alpha: alpha
)
}
}

像这样用在任何地方

let color1 = UIColor(hex: 0xffffff)
let color2 = UIColor(hex: 0xffffff, alpha: 0.2)

下面是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
)
}
}

我为它创建了一个便利的init:

extension UIColor {
convenience init(hex: String, alpha: CGFloat)
{
let redH = CGFloat(strtoul(hex.substringToIndex(advance(hex.startIndex,2)), nil, 16))
let greenH = CGFloat(strtoul(hex.substringWithRange(Range<String.Index>(start: advance(hex.startIndex, 2), end: advance(hex.startIndex, 4))), nil, 16))
let blueH = CGFloat(strtoul(hex.substringFromIndex(advance(hex.startIndex,4)), nil, 16))


self.init(red: redH/255, green: greenH/255, blue: blueH/255, alpha: alpha)
}
}

然后你可以在项目的任何地方创建一个UIColor,就像这样:

UIColor(hex: "ffe3c8", alpha: 1)

希望这对你有所帮助……

斯威夫特的版本。作为函数或扩展使用。

函数
  func UIColorFromRGB(colorCode: String, alpha: Float = 1.0) -> UIColor{
var scanner = NSScanner(string:colorCode)
var color:UInt32 = 0;
scanner.scanHexInt(&color)
    

let mask = 0x000000FF
let r = CGFloat(Float(Int(color >> 16) & mask)/255.0)
let g = CGFloat(Float(Int(color >> 8) & mask)/255.0)
let b = CGFloat(Float(Int(color) & mask)/255.0)
    

return UIColor(red: r, green: g, blue: b, alpha: CGFloat(alpha))
}
扩展
extension UIColor {
convenience init(colorCode: String, alpha: Float = 1.0){
var scanner = NSScanner(string:colorCode)
var color:UInt32 = 0;
scanner.scanHexInt(&color)
        

let mask = 0x000000FF
let r = CGFloat(Float(Int(color >> 16) & mask)/255.0)
let g = CGFloat(Float(Int(color >> 8) & mask)/255.0)
let b = CGFloat(Float(Int(color) & mask)/255.0)
        

self.init(red: r, green: g, blue: b, alpha: CGFloat(alpha))
}
}
如何打电话
let hexColorFromFunction = UIColorFromRGB("F4C124", alpha: 1.0)
let hexColorFromExtension = UIColor(colorCode: "F4C124", alpha: 1.0)
您还可以从接口构建器中定义Hex Color

enter image description here

使用任何转换器网站将十六进制颜色转换为RGB值(如果你谷歌“十六进制到RGB”,你会看到一吨)。例如,这个:http://www.rgbtohex.net/hextorgb/

然后将颜色属性更改为UIColor。例子:

self.profilePicture.layer.borderColor = [UIColor colorWithRed:0 green:167 blue:142 alpha:1.0].CGColor;

十六进制颜色值是:00a78e转换为RGB: R: 0 G: 167 B: 142

如果你给出的RGB值不在0到1.0之间,你必须将它们除以255。例子:

self.profilePicture.layer.borderColor = [UIColor colorWithRed:83.00/255.0 green:123.00/255.0 blue:53.00/255.0 alpha:1.0].CGColor;
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

抛光扩展从原来的答案@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 {

// MARK: - getColorFromHex /** 此函数将颜色十六进制代码转换为RGB

- parameter color  hex string.


- returns: RGB color code.
*/
class func getColorFromHex(hexString:String)->UIColor{


var rgbValue : UInt32 = 0
let scanner:NSScanner =  NSScanner(string: hexString)


scanner.scanLocation = 1
scanner.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))
}

在swift中,我用以下方法创建了一个类扩展,将十六进制代码转换为UIColor。

extension UIColor {
convenience init(R: CGFloat, G: CGFloat, B: CGFloat, alpha: CGFloat) {
self.init(red: R/255.0, green: G/255.0, blue: B/255.0, alpha: alpha)
}


class func colorWithHex(hex: UInt, alpha: CGFloat) -> UIColor {
return UIColor(R: CGFloat((hex & 0xFF0000) >> 16), G: CGFloat((hex & 0x00FF00) >> 8), B: CGFloat(hex & 0x0000FF), alpha: alpha)
}
}

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))
}
}
此代码包括字符串格式检查。 例如< / p >
let aColor = UIColor(hexString: "#dadada")!
let failed = UIColor(hexString: "123zzzz")

据我所知,我的代码在维护可失败条件的语义和返回可选值方面没有任何缺点。这应该是最好的答案。

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)")


}

斯威夫特2.0版本的解决方案,将处理alpha值的颜色和完美的错误处理:

func RGBColor(hexColorStr : String) -> UIColor?{


var red:CGFloat = 0.0
var green:CGFloat = 0.0
var blue:CGFloat = 0.0
var alpha:CGFloat = 1.0


if hexColorStr.hasPrefix("#"){


let index   = hexColorStr.startIndex.advancedBy(1)
let hex     = hexColorStr.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0


if scanner.scanHexLongLong(&hexValue)
{
if hex.characters.count == 6
{
red   = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8)  / 255.0
blue  = CGFloat(hexValue & 0x0000FF) / 255.0
}
else if hex.characters.count == 8
{
red   = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue  = CGFloat((hexValue & 0x0000FF00) >> 8)  / 255.0
alpha = CGFloat(hexValue & 0x000000FF)         / 255.0
}
else
{
print("invalid hex code string, length should be 7 or 9", terminator: "")
return nil
}
}
else
{
print("scan hex error")
return nil
}
}


let color: UIColor =  UIColor(red:CGFloat(red), green: CGFloat(green), blue:CGFloat(blue), alpha: alpha)
return color
}

斯威夫特2.0:

将此方法添加到VC或扩展UIColor。

func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString


if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}


if (cString.characters.count != 6) {
return UIColor.grayColor()
}


let rString = (cString as NSString).substringToIndex(2)
let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)


var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)




return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}

用法:

    loginButton.tintColor = self.colorWithHexString("#be1337")


OR


let hexColor = self.colorWithHexString("#be1337")

你可以使用这个库

https://github.com/burhanuddin353/TFTColor

斯威夫特

UIColor.colorWithRGB(hexString: "FF34AE" alpha: 1.0)

objective - c

[UIColor colorWithRGBHexString:@"FF34AE" alpha:1.0f]

伊森·斯特里德的回答的Swift 3示例。一个接受十六进制字符串并返回UIColor的函数 (你可以输入十六进制字符串格式:#ffffffffffff)

例子:

func hexStringToUIColor (hex:String) -> UIColor {
var cString: String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()


if (cString.hasPrefix("#")) {
if let range = cString.range(of: cString) {
cString = cString.substring(from: cString.index(range.lowerBound, offsetBy: 1))
}
}


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)
)
}

用法:

var color1 = hexStringToUIColor("#d3d3d3")

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
{
class func fromHexaString(hex:String) -> UIColor
{
let scanner           = Scanner(string: hex)
scanner.scanLocation  = 0
var rgbValue: UInt64  = 0
scanner.scanHexInt64(&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)
)
}
}


//you can call like this.


UIColor.fromHexaString(hex:3276b1)
    //UIColorWithHexString


static UIColor * UIColorWithHexString(NSString *hex) {
unsigned int rgb = 0;
[[NSScanner scannerWithString:
[[hex uppercaseString] stringByTrimmingCharactersInSet:
[[NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEF"] invertedSet]]]
scanHexInt:&rgb];
return [UIColor colorWithRed:((CGFloat)((rgb & 0xFF0000) >> 16)) / 255.0
green:((CGFloat)((rgb & 0xFF00) >> 8)) / 255.0
blue:((CGFloat)(rgb & 0xFF)) / 255.0
alpha:1.0];
}

使用

self.view.backgroundColor = UIColorWithHexString(@"#0F35C0");

十六进制初始化

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")

编码愉快!享受! !

Xamarin的。iOS你可以使用下面的宏来代替宏:

public UIColor UIColorFromHexValue(int value, float alpha = 1f) =>
UIColor.FromRGBA(
((value & 0xFF0000) >> 16) / 255.0f,
((value & 0x00FF00) >> 16) / 255.0f,
((value & 0x0000FF) >> 16) / 255.0f,
alpha);

用法类似:

label.TextColor = UIColorFromHexValue(0xBC1128);

# EYZ0

你可以像这样在扩展中创建一个漂亮的convenience构造函数:

extension UIColor {
convenience init(hexString: String, alpha: CGFloat = 1.0) {
var hexInt: UInt32 = 0
let scanner = Scanner(string: hexString)
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
scanner.scanHexInt32(&hexInt)


let red = CGFloat((hexInt & 0xff0000) >> 16) / 255.0
let green = CGFloat((hexInt & 0xff00) >> 8) / 255.0
let blue = CGFloat((hexInt & 0xff) >> 0) / 255.0
let alpha = alpha


self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}

以后再用

let color = UIColor(hexString: "#AABBCCDD")
self.view.backgroundColor = colorWithHex(hex: yourColorCode)
  • hexaDecimalCode创建颜色的代码
func colorWithHex (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)
)
}

张贴参考网站我刚刚发现。 它做了所有的脏工作,从HEX或RGB开始,在ObjC, Swift和Xamarin中打印出代码

https://www.uicolor.xyz/#/hex-to-ui

使用Xcode的原生颜色文字特性来轻松地添加十六进制颜色。

在代码中输入Color Literal,让Xcode自动完成其余的工作。

颜色选择器UI将允许您粘贴十六进制颜色:#FF9300

color picker

宏的git差异将显示RGB值而不是十六进制值:

let orange = #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1)

但它仍然是一种简单的方法来粘贴十六进制没有任何第三方工具或扩展。

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)
}

大多数发布的解决方案使用Scanner,但至少在现代Swift中你真的不需要它。相反,你可以简单地使用基数为16的UInt初始化,然后使用基本的二进制操作来获得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",你可能需要删除开头哈希符号(#),如果你的字符串中有一个。