ChatGPT解决这个技术问题 Extra ChatGPT

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

如何从 十六进制 字符串格式(例如 #00FF00)创建 UIColor


T
Top-Master

我发现最简单的方法是使用宏。只需将它包含在您的标题中,它就可以在您的整个项目中使用。

#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 macro with hex values

此代码的格式化版本:

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

这很好,只是它没有按照提问者的要求进行,即将十六进制字符串转换为 UIColor。这会将整数转换为 UIColor。
@MohamedA.Karim 这是从十六进制格式整数(0x ...)而不是十六进制格式字符串(“#...”)返回 UIColor 的示例。如果这是您想要的,但不是提问者要求的,那就太好了。
@ScottKohlert您的代码行将一个十六进制格式字符串(以“#”为前缀)转换为另一个十六进制格式字符串(以“0x”为前缀)。它不产生整数。
如何像 [UIColor whiteColor].CGColor 一样使用它?
要将十六进制格式字符串转换为整数以用于此宏,请参阅 stackoverflow.com/questions/3648411/…
T
Top-Master

一个简洁的解决方案:

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

可以在此处找到进行反向转换的好方法(例如,如果您将颜色存储在核心数据/远程数据库中) - stackoverflow.com/questions/11884227/…
一个完美的解决方案。如果您的十六进制字符串来自(文档记录非常差的)API,请务必针对 #FFF 或 #FC0 等速记十六进制代码进行测试。您需要将它们更改为#FFFFFF/#FFCCOO。
您可能还想在 setScanLocation 行之前添加 if ( [hexString rangeOfString:@"#"].location == 0 ) 以使 # 可选。
你能添加反向方法吗?
对于懒人:SWIFT 版本 here
T
Top-Master

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

colorComponentFrom:start:length: 中,您不应该有 return hexComponent / 0xFF; // divide by 255, not 256 吗?您应该返回的最大十六进制值是 0xFF,因此这就是您应该除以 0xFF (255) 的值。
好抓住山姆。编辑以反映更改。
这太棒了,干杯。此外,您可以在 NSString 上创建一个类别,而不是 UIColor 上的类别,以便能够具有像 [@"#538aa4" toColor] 这样的语法
这个解决方案很棒,我建议为私有接口的名称添加“Private”以避免编译器警告。 @interface UIColor(私人)
好的。不过,您应该将其他功能放在界面中。
T
Tommie C.

关于如何解决 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);

Complete Reference Article

斯威夫特 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
}

斯威夫特 5 (iOS 13)+

下面显示了在 SDK 弃用 scanHexInt32 的情况下有效的更新。我已将代码包装到 Swift 游乐场文件中。

//: 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 颜色名称和代码 颜色十六进制颜色代码


此处发布的 Swift 片段似乎误解了 Swift 中可选项的目的,即包含可能永远不存在的值。参数是否需要是可选的问题是是否有人可能需要将其设置为 nil 的能力。 alpha永远设置为 nil 是否有意义?因为这种方法赋予了人们这种能力,如果有人决定将 alpha 设置为 nil,那么强制解开该可选选项总是会导致崩溃。不过,我还没有把它编辑掉,以防有一些我不知道的理由。
@JonathanThornton - 感谢您的提醒。解决。
在遗留项目上工作,Objective-C 解决方案运行良好......除了......奇怪......@“#ffc107”和@“#e040fb”拒绝合作!想法?
'scanHexInt32' 在 macOS 10.15 中已弃用
@Sentry.co - 更新代码以处理不推荐使用的方法。
E
Ethan Strider

这是一个接受十六进制字符串并返回 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。
这是速记符号,其中“#F0F”等价于“#FF00FF”。编写一个检查速记并扩展它的函数会很简单。
S
Stan James

使用这个类别:

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

没有阿尔法处理
a
aheze

您可以像这样进行扩展

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)

死简单,绝对是我的最爱。
谢谢,这个很棒,与其他文字墙相比如此简洁!
不错的功能,但它并不能以任何方式回答问题。
@mah这正是我认为的问题,如何从十六进制字符串创建 UIColor
@ManuGupta,您可能会注意到此答案中完全没有任何字符串处理。十六进制数不是十六进制字符串。该问题明确说明了一个字符串,尽管其中没有引号,但 #00FF00 显然是一个字符串。正如其他人所说,它很简单,简洁。但如果它不处理字符串,它就不可能回答询问如何处理字符串的问题。
C
Community

一个很棒的 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 source
Subscript source

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

您是否还使用字符串扩展来获取其下标?例如stackoverflow.com/a/24144365/3220708
@CraigGrummitt 哦,天哪!哈哈,是的。我有一个不错的扩展和下标编译列表,我有时(遗憾地)忘记了标准语言功能集中包含和不包含的内容。我更新了我的答案,包括您提供的来源。不确定我是否从那里得到它,但它确实看起来很接近。
您可能想提到它是一个字符串扩展。此外,您似乎错过了 String floatValue 扩展:stackoverflow.com/a/24088249/3220708 除此之外,干得好!
countElements() 函数在哪里?
countElements() 在 Swift 1.2 中被替换为 count(),它内置在语言中。我更新了我的答案以反映这一点。
A
Ashish Kakkad

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


+1 如果你向下滚动,有问题的方法是 +colorWithHexString:。
@RobNapier +colorWithHexString: 不起作用。至少在我的情况下。 :)
L
Leo Dabus
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

有史以来最好的简短解决方案
A
Ashish Kakkad

我为此找到了一个很好的 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 好的,我添加了实现代码:)
C
Community

快捷版。用作函数或扩展。

  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)

十六进制颜色

https://i.stack.imgur.com/Nlf4X.png


G
George Maisuradze

斯威夫特 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 中已弃用
T
Tieme

这是另一种选择。

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

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

您可以使用各种在线工具将 HEX 字符串转换为实际的 UIColor。查看 uicolor.orgUI Color Picker。输出将被转换为 Objective-C 代码,例如:

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

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


另一个在线工具,实际上同名,UI Color Picker
通常,当人们寻求代码帮助以解决这样一个相当简单的问题时,“首先访问某个在线站点......”的答案实际上与提问者想要的答案相差甚远。
N
Nath

这很好,有 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]

漂亮的东西兄弟:)
g
gheese

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

h
hris.to

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)

如果您希望能够从字符串中使用它,您可以使用 strtoul:

var hexString = "0x7F00FFFF"

let num = strtoul(hexString, nil, 16)

var colorFromString = colorWithHex(num)

M
Morgan Wilde

这是作为 UIColor 的扩展编写的 Swift 1.2 版本。这可以让你做

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

在以 let greenRange = ... 开头的行的 Xcode 6.3.2 中,我得到一个异常:fatal error: can not increment endIndex
@CliftonLabrum 我已经在 Xcode 7 beta 3 上测试过了,它的工作原理是一样的。你还有这个问题吗?
D
David Kyslenko

斯威夫特 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)
}

R
Renato Lochetti

另一个允许使用 "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];
}

R
RiceAndBytes

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

}

B
Bartłomiej Semańczyk

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

V
Vinayak
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)

M
MLQ

我最终为 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

起初我喜欢并尝试了上面的#define 方法。然而,就像大多数带有 many () 的定义一样,它很难扩展和调试。然后我回到“实用程序”类方法方法。这可行,但它在命名空间中引入了一个新的类名。然后,我看到了你的帖子,我很喜欢它,因为它了解如何使用 Objective-C 语言。不错的演出。我计划制作一个采用 RGB 十进制值的类似解决方案(例如红色:24 绿色:104 蓝色:255)
s
steveSarsawa
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)
    )
}

M
Manish Saini
 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];只要....
a
adali

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

L
Lucas Martins Juviniano

我为此创建了一个方便的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)

希望这可以帮助...


A
Abhishek Verma

您可以将 UIColor 的扩展类创建为:-

扩展 UIColor {

// MARK: - getColorFromHex /** 此函数将颜色 Hex 代码转换为 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))
}

}