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


当前回答

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

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

其他回答

我找到了一个很好的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
 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;
    }

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

在你的代码中输入颜色文字,然后让Xcode自动完成剩下的工作。

颜色选择界面将允许你粘贴十六进制颜色:#FF9300

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

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

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

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

使用这个类别:

在文件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"

and:

[UIColor colorWithHexString:@"#6e4b4b"];