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


Answers:


722

我发现最简单的方法是使用宏。只需将其包括在标题中,即可在整个项目中使用。

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

130
这很不错,只是它不执行发问者要问的事情,即将十六进制的STRING转换为UIColor。这会将整数转换为UIColor。
darrinm 2012年

31
@ MohamedA.Karim这是从十六进制格式的整数(0x ...)而不是十六进制格式的字符串(“#...”)返回UIColor的示例。很好,如果那是您想要的,但不是发问者的要求。
darrinm

3
@ScottKohlert您的代码行将一个十六进制格式字符串(以“#”为前缀)转换为另一十六进制格式字符串(以“ 0x”为前缀)。它不会产生整数。
darrinm

1
如何使用[UIColor whiteColor] .CGColor这样的字体?
SleepNot

3
要将十六进制格式的字符串转换为整数以供此宏使用,请参见stackoverflow.com/questions/3648411/…
devios1 2014年

371

简洁的解决方案:

// 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];
}

1
而对于做反向转换(比如,你要存储的核心数据/远程数据库的颜色),可以在这里找到一个好方法- stackoverflow.com/questions/11884227/...
埃里克·戈德堡

1
完美的解决方案。如果您的十六进制字符串来自(非常不完整的文档)API,请确保对照#FFF或#FC0之类的速记十六进制代码进行测试。您需要将它们更改为#FFFFFF /#FFCCOO。
Patrick

10
您可能还想if ( [hexString rangeOfString:@"#"].location == 0 )在该setScanLocation行之前添加以使其为#可选。
devios1 2015年

可以添加相反的方法吗?
哈桑2015年

11
对于懒惰者:此处为SWIFT版本。
fabian789 2015年

188

我有一个与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 

3
colorComponentFrom:start:length:,你不应该return hexComponent / 0xFF; // divide by 255, not 256吗?您应该取回的最大十六进制值为0xFF,因此应除以0xFF(255)。
山姆

很好,山姆。编辑以反映更改。
米卡·海因琳

6
太好了,欢呼。另外,除了UIColor上的类别外,您还可以在NSString上创建一个类别,使其具有如下语法:[@"#538aa4" toColor]
Dan2552 2012

2
这个解决方案很棒,我建议为私有接口的名称添加“ Private”,以避免编译器警告。@interface UIColor(Private)
djleop

1
真好 不过,您应该将其他功能放在界面中。
比约恩·罗奇

63

关于如何解决OP UIColor从十六进制字符串中提取a的问题,有一篇不错的文章。下面介绍的解决方案与其他解决方案有所不同,因为它支持可能包含以十六进制字符串表示形式开头的'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。我还UInt32根据NSScannerSwift 2.2中的类的要求将int类型更新为。

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+

将相同的逻辑应用于迅速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
}

颜色十六进制参考

HTML颜色名称和代码

颜色十六进制颜色代码


此处发布的Swift代码片段似乎误解了Swift中可选参数的目的,即包含可能永远不存在的值。关于参数是否需要为可选参数的问题是,是否有人需要将其设置为nil的能力。是否有可能使意义alpha永远被设为零?因为此方法使人们具有这种能力,并且如果有人决定将其设置alpha为nil,则强制展开该可选内容将不可避免地导致崩溃。不过,如果有一些我不知道的理由,我还没有进行编辑。
乔纳森·桑顿

@JonathanThornton-感谢大家的注意。解决。
Tommie C.

在遗留项目和Objective-C解决方案上的工作非常顺利...除了...奇怪的是... @“#ffc107”和@“#e040fb”拒绝合作!有什么想法吗?
纳撒尼尔(Nathaniel)

51

此函数需要一个十六进制字符串并返回UIColor。
(您可以输入以下格式的十六进制字符串:#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)
    )
}



资料来源:arshad / gist:de147c42d7b3063ef7bc


我在SVG中看到过,那里有一个小版本的十六进制字符串,带有3个字符,例如#F0F。
Glenn Howes

这是速记符号,其中“#F0F”等效于“#FF00FF”。编写一个检查速记并将其扩展的函数会很简单。
伊桑·史翠德

38

使用此类别:

在文件UIColor + Hexadecimal.h中

#import <UIKit/UIKit.h>

@interface UIColor(Hexadecimal)

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

@end

在文件UIColor + 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"];

没有阿尔法处理
伊霍尔·克里莫夫

28

一个很棒的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)
        )
    }
}

字符串扩展:
Float源下
标源

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

您是否还在使用String扩展名来获取其下标?例如stackoverflow.com/a/24144365/3220708
Craig Grummitt 2015年

@CraigGrummitt哦,天哪!哈哈,是的。我有一份不错的扩展名和下标的已编译列表,有时(很难)忘记了标准语言功能集中包含的内容和不包含的内容。我更新了我的答案,包括您提供的来源。不知道我是否从那儿拿到了它,但是看起来确实很近。
菲罗(Firo)

您可能要提到这是一个String扩展名。您似乎还错过了String floatValue扩展名:stackoverflow.com/a/24088249/3220708除此之外,还不错!
Craig Grummitt 2015年

countElements()函数在哪里?
ΕГИІИО

countElements()count()在Swift 1.2中被替换,它已内置在语言中。我更新了答案以反映这一点。
菲罗,2015年

27

您可以这样扩展

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

并在这样的任何地方使用

UIColor(rgb: 0xffffff, alphaVal: 0.2)

死法简单,绝对是我的最爱。
理论

谢谢,这很棒,与其他文字墙相比非常简洁!
FrankByte.com

不错的功能,但它不能以任何方式回答问题。
玛哈

@mah这正是我认为的问题,如何从十六进制字符串创建UIColor
Manu Gupta

@ManuGupta您可能会注意到此答案中完全没有任何字符串处理。十六进制数字不是十六进制字符串。该问题明确声明了一个字符串,尽管其中没有引号,但#00FF00显然打算将其作为字符串。正如其他人所说,这很简单,简洁。但是,如果它不处理字符串,就不可能回答询问如何处理字符串的问题。
mah

26

没有从十六进制字符串到UIColor(或CGColor)我知道的内建转换。但是,您可以轻松地为此目的编写几个函数-例如,请参阅iphone开发访问uicolor组件


3
+1如果向下滚动,则相关方法为+ colorWithHexString:。
罗布·纳皮尔

1
@RobNapier +colorWithHexString:不起作用。至少就我而言。:)
2012年

15

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

@PeterDuniho好的,我添加了实现代码:)
Hlung

13

快速版本。用作功能或扩展。

功能
  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来自界面”构建器。

在此处输入图片说明


12

这是另一种选择。

- (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];
}

替代问题的替代答案...虽然不是此页面上问题的合理答案。
玛哈

11

您可以使用各种在线工具将十六进制字符串转换为实际的UIColor。请查看uicolor.orgUI颜色选择器。输出将转换为Objective-C代码,例如:

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

您可以将其嵌入到应用程序中。希望这可以帮助!


另一个在线工具,实际上是同名UI Color Picker

通常,当人们寻求代码帮助来解决这样一个非常简单的问题时,回答为“首先访问某个在线站点...”的答案实际上甚至几乎不是问询者想要的答案。
麻将

11

SWIFT 4

您可以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")

“ scanHexInt32”已在iOS 13.0中弃用
Cosmo Arun

10
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

7

这对cocoapod的支持很好

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]

美丽的东西兄弟:)
cesarferreira 2014年

4

带有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)]

4

尽管收到RGBA Int值以支持透明度,但Swift等效于@Tom的答案:

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)

如果想从字符串中使用它,可以使用strtoul:

var hexString = "0x7F00FFFF"

let num = strtoul(hexString, nil, 16)

var colorFromString = colorWithHex(num)

4

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

在Xcode 6.3.2开头的行中,let greenRange = ...我得到一个例外:fatal error: can not increment endIndex
Clifton Labrum 2015年

@CliftonLabrum我已经在Xcode 7 beta 3上对此进行了测试,并且工作原理相同。您还有这个问题吗?
Morgan Wilde

3

另一种实现允许使用类似于"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];
}

3

更新为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))

}

3

创建以下内容的优雅扩展名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") 

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

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

如果要使用此代码,则调用[self getUIColorObjectFromHexString:@“ 27b8c8” alpha:9];只有....
马尼什赛尼

2

我喜欢确保颜色之外的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

2

我为此创建了一个方便的初始化:

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)

希望这可以帮助...


2

您可以通过以下方式创建UIColor的扩展类:

扩展UIColor {

//标记:-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))
}

}


2

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

据我所知,我的代码在保持可失败条件的语义并返回可选值方面没有任何不利之处。这应该是最好的答案。


2

Swift 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
    //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");
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.