我如何创建一个十六进制字符串 UIColor?

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

转载于:https://stackoverflow.com/questions/1560081/how-can-i-create-a-uicolor-from-a-hex-string

csdnceshi70
笑故挽风 Here is another library: github.com/burhanuddin353/TFTColor
3 年多之前 回复
csdnceshi75
衫裤跑路 Erica also has a great color extension category for iOS and OSX.
大约 7 年之前 回复

30个回答

A concise solution:

// 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];
}
csdnceshi54
hurriedly% if i pass the value "364050" string to colorFromHexString its gives different color, do I need to include #364050 ?
3 年多之前 回复
csdnceshi52
妄徒之命 Heh [scanner setScanLocation:[hexString rangeOfString:@"#"].location+1];
接近 5 年之前 回复
weixin_41568110
七度&光 For the lazy: SWIFT version here.
接近 5 年之前 回复
csdnceshi57
perhaps? can you please add the reverse method.
大约 5 年之前 回复
weixin_41568126
乱世@小熊 You might also want to add if ( [hexString rangeOfString:@"#"].location == 0 ) before the setScanLocation line to make the # optional.
大约 5 年之前 回复
csdnceshi64
游.程 A perfect solution. If your hex string comes from a (very poorly documented) API, be sure to test against shorthand hex codes like #FFF or #FC0. You'll need to change them to #FFFFFF/#FFCCOO.
5 年多之前 回复
csdnceshi75
衫裤跑路 And a good method for doing the reverse conversion (like if you're storing colors in core data / a remote database) can be found here - stackoverflow.com/questions/11884227/…
6 年多之前 回复

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);
csdnceshi52
妄徒之命 There is an advantage to using as a macro but you won't find it in this particular solution, however had the macro used the ## operator then your input could be just FF0000 instead of 0xFF0000 which would be nice for lots of coders copy pasting hex colors from, say, photoshop. To accomplish this, just replace occurrences of rgbValue with 0x ## rgbValue in the body of macro.
一年多之前 回复
weixin_41568126
乱世@小熊 online converter webpagefx.com/web-design/hex-to-rgb
3 年多之前 回复
csdnceshi68
local-host Is there any advantage using a macro instead of a function?
5 年多之前 回复
csdnceshi79
python小菜 To convert a hex format string to an integer for use with this macro, see stackoverflow.com/questions/3648411/….
接近 6 年之前 回复
csdnceshi73
喵-见缝插针 How to use this like [UIColor whiteColor].CGColor?
6 年多之前 回复
csdnceshi56
lrony* Perhaps some day the OP will return to bless one of these answers and we'll know for sure :). I assume Rupesh is dealing with the string at runtime, in which case what matters is converting the "#00FF00" string into parameters accepted by one of UIColor's constructors. Several answers here show ways to do this, but not the one we're commenting on.
7 年多之前 回复
csdnceshi70
笑故挽风 the OP was looking for a string format starting with a #, I just added the line of code so it would convert the # into the format required by the #define statement (Ox...). See the OP's question: How can I create a UIColor from a hexadecimal STRING format, such as #00FF00
7 年多之前 回复
csdnceshi56
lrony* Your line of code converts one hex format string (prefixed with "#") into another hex format string (prefixed with "0x"). It does not produce an integer.
7 年多之前 回复
csdnceshi70
笑故挽风 withString:@"0x").
7 年多之前 回复
csdnceshi56
lrony* That is an example of returning a UIColor from a hex format integer (0x...) not a hex format string ("#..."). Great if that's what you want, but not what the questioner asked for.
7 年多之前 回复
csdnceshi56
lrony* This is great except it doesn't do what the questioner asks, which is to convert a hex STRING into a UIColor. This converts an integer to a UIColor.
接近 8 年之前 回复

I've got a solution that is 100% compatible with the hex format strings used by Android, which I found very helpful when doing cross-platform mobile development. It lets me use one color palate for both platforms. Feel free to reuse without attribution, or under the Apache license if you prefer.

#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 
csdnceshi53
Lotus@ How to catch exception in swift? thoughts
2 年多之前 回复
csdnceshi54
hurriedly% Nice. You should put the other function in the interface, though.
大约 5 年之前 回复
csdnceshi79
python小菜 Nice solution. However imo it should also be able to handle hexString=nil and give black
接近 6 年之前 回复
csdnceshi65
larry*wei Why isn't colorWithHexString declared in the interface?
接近 6 年之前 回复
csdnceshi59
ℙℕℤℝ I agree with @djleop and edited the post accordingly.
7 年多之前 回复
csdnceshi67
bug^君 This solution is great, I would suggest to add "Private" for the name of the private interface to avoid a compiler warning. @interface UIColor(Private)
7 年多之前 回复
csdnceshi60
℡Wang Yan This is great, cheers. Also, instead of a category on UIColor you could make one on NSString to be able to have syntax like [@"#538aa4" toColor]
接近 8 年之前 回复
csdnceshi70
笑故挽风 Good catch Sam. Edited to reflect the change.
接近 9 年之前 回复
weixin_41568110
七度&光 in colorComponentFrom:start:length:, shouldn't you have return hexComponent / 0xFF; // divide by 255, not 256 ? The largest hex value you should get back is 0xFF, thus that is what you should be dividing by 0xFF (255).
接近 9 年之前 回复

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)
        }
    }
}
weixin_41568208
北城已荒凉 You are correct. I have fixed the comment. Thanks for pointing it out (feel free to edit things like that).
4 年多之前 回复
csdnceshi59
ℙℕℤℝ You know what? There is a bug in your code! In the first commented line and in the next one, you should replace #GGRRBBAA by #RRGGBBAA, should not you? ;-)
4 年多之前 回复
weixin_41568208
北城已荒凉 countElements() was replaced with count() in Swift 1.2, it is built into the language. I updated my answer to reflect that.
大约 5 年之前 回复
csdnceshi70
笑故挽风 Where is countElements() func?
大约 5 年之前 回复
csdnceshi78
程序go You might want to mention that it's a String extension. Also you seem to have missed String floatValue extension: stackoverflow.com/a/24088249/3220708 Other than that, good work!
5 年多之前 回复
weixin_41568208
北城已荒凉 oh my! Haha, yes. I have a decent compiled list of extensions and subscripts I sometimes (sadly) forget what is and is not included in the standard language feature set. I updated my answer including the source you gave. Not sure if I even got it from there but it sure looks close.
5 年多之前 回复
csdnceshi78
程序go Are you also using a String extension to get its subscript? eg stackoverflow.com/a/24144365/3220708
5 年多之前 回复

You could use various online tools to convert a HEX string to an actual UIColor. Check out uicolor.org or UI Color Picker. The output would be converted into Objective-C code, like:

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

Which you could embed in your application. Hope this helps!

csdnceshi62
csdnceshi62 Another online tool, same name in fact, UI Color Picker.
6 年多之前 回复

Create elegant extension for 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)
    }
}

Create red color:

let red = UIColor(string: "#ff0000") 

You can create extension class of UIColor as:-

extension UIColor {

// MARK: - getColorFromHex /** This function will convert the color Hex code to 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))
}

}

swift version. Use as a Function or an Extension.

Function
  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
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))
    }
}
How to call
let hexColorFromFunction = UIColorFromRGB("F4C124", alpha: 1.0)
let hexColorFromExtension = UIColor(colorCode: "F4C124", alpha: 1.0)
You can also define your Hex Color from interface builder.

enter image description here

This is nice with cocoapod support

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]
csdnceshi75
衫裤跑路 Beautiful stuff bro :)
大约 6 年之前 回复

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)
共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐