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


当前回答

抛光扩展从原来的答案@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 *)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创建了一个类别,我可以在我的其他项目中重用,并添加了这个函数:

+ (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

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

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

我发现最简单的方法是使用宏。只要把它包括在你的标题中,它就可以在你的整个项目中使用。

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

迅速:

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