How can I create a UIColor from a hex string?

后端 未结 30 1125
北恋
北恋 2020-11-22 16:53

How can I create a UIColor from a hexadecimal string format, such as #00FF00?

相关标签:
30条回答
  • 2020-11-22 17:16
    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)}
    }
    

    Usage:

    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
    
    0 讨论(0)
  • 2020-11-22 17:18

    I've found the simplest way to do this is with a macro. Just include it in your header and it's available throughout your project.

    #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

    Also formatted version of this code:

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

    Usage:

    label.textColor = UIColorFromRGB(0xBC1128);
    
    0 讨论(0)
  • 2020-11-22 17:18

    Use this Category :

    in the file UIColor+Hexadecimal.h

    #import <UIKit/UIKit.h>
    
    @interface UIColor(Hexadecimal)
    
    + (UIColor *)colorWithHexString:(NSString *)hexString;
    
    @end
    

    in the file 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
    

    In Class you want use it :

    #import "UIColor+Hexadecimal.h"
    

    and:

    [UIColor colorWithHexString:@"#6e4b4b"];
    
    0 讨论(0)
  • 2020-11-22 17:18

    A great Swift implementation (updated for Xcode 7) using extensions, pulled together from a variety of different answers and places. You will also need the string extensions at the end.

    Use:

    let hexColor = UIColor(hex: "#00FF00")
    

    NOTE: I added an option for 2 additional digits to the end of the standard 6 digit hex value for an alpha channel (pass in value of 00-99). If this offends you, just remove it. You could implement it to pass in an optional alpha parameter.

    Extension:

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

    String extensions:
    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)
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:20

    Swift equivalent of @Tom's answer, although receiving RGBA Int value to support transparency:

    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)
    

    And if you want to be able to use it from string you could use strtoul:

    var hexString = "0x7F00FFFF"
    
    let num = strtoul(hexString, nil, 16)
    
    var colorFromString = colorWithHex(num)
    
    0 讨论(0)
  • 2020-11-22 17:20

    I like to ensure the alpha besides the color, so i write my own category

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

    easy to use like this

    [UIColor colorWithHex:0xFF0000FF]; //Red
    [UIColor colorWithHex:0x00FF00FF]; //Green
    [UIColor colorWithHex:0x00FF00FF]; //Blue
    [UIColor colorWithHex:0x0000007F]; //transparent black
    
    0 讨论(0)
提交回复
热议问题