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


当前回答

斯威夫特4

你可以像这样在扩展中创建一个非常方便的构造函数:

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

其他回答

据我所知,没有从十六进制字符串到UIColor(或CGColor)的内置转换。但是,您可以很容易地为此目的编写几个函数—例如,参见iphone开发访问uicolor组件

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

使用这个类别:

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

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

使用任何转换器网站将十六进制颜色转换为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;