如何将 HEX RGB 颜色代码转换为 UIColor?

发布于 2024-09-25 06:16:13 字数 83 浏览 0 评论 0原文

我有一个像 #ffffff 这样的 RGB 十六进制代码作为 NSString,并且想要将其转换为 UIColor。有没有一种简单的方法可以做到这一点?

I have an RGB hex code like #ffffff as NSString and want to convert that into an UIColor. Is there a simple way to do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

懒的傷心 2024-10-02 06:16:13

在我的一些代码中,我使用了 2 个不同的函数:

void SKScanHexColor(NSString * hexString, float * red, float * green, float * blue, float * 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];

  if (red) { *red = ((baseValue >> 24) & 0xFF)/255.0f; }
  if (green) { *green = ((baseValue >> 16) & 0xFF)/255.0f; }
  if (blue) { *blue = ((baseValue >> 8) & 0xFF)/255.0f; }
  if (alpha) { *alpha = ((baseValue >> 0) & 0xFF)/255.0f; }
}

然后我这样使用它:

UIColor * SKColorFromHexString(NSString * hexString) {
  float red, green, blue, alpha;
  SKScanHexColor(hexString, &red, &green, &blue, &alpha);

  return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

如果您更喜欢将其用作一个 UIColor 类别,那么只需更改几行即可:

+ (UIColor *) colorFromHexString:(NSString *)hexString {
  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;
  float alpha = ((baseValue >> 0) & 0xFF)/255.0f;

  return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

这将处理“#abc”、“#abcdef31”等字符串。

In some code of mine, I use 2 different functions:

void SKScanHexColor(NSString * hexString, float * red, float * green, float * blue, float * 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];

  if (red) { *red = ((baseValue >> 24) & 0xFF)/255.0f; }
  if (green) { *green = ((baseValue >> 16) & 0xFF)/255.0f; }
  if (blue) { *blue = ((baseValue >> 8) & 0xFF)/255.0f; }
  if (alpha) { *alpha = ((baseValue >> 0) & 0xFF)/255.0f; }
}

And then I use it like this:

UIColor * SKColorFromHexString(NSString * hexString) {
  float red, green, blue, alpha;
  SKScanHexColor(hexString, &red, &green, &blue, &alpha);

  return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

If you prefer to use this as a UIColor category, then it's just a matter of altering a few lines:

+ (UIColor *) colorFromHexString:(NSString *)hexString {
  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;
  float alpha = ((baseValue >> 0) & 0xFF)/255.0f;

  return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

This will handle strings like "#abc", "#abcdef31", etc.

远山浅 2024-10-02 06:16:13

如果您使用十六进制值..

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

  //Then use any Hex value

 self.view.backgroundColor = UIColorFromRGB(0xD2691E);   

If you are using Hex Values..

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

  //Then use any Hex value

 self.view.backgroundColor = UIColorFromRGB(0xD2691E);   
马蹄踏│碎落叶 2024-10-02 06:16:13

我一直在寻找一个简单的解决方案,并想出了这个(不完全是 Objective-C,但工作起来就像一个魅力):

NSString *stringColor = @"#AABBCC";
NSUInteger red, green, blue;
sscanf([stringColor UTF8String], "#%02X%02X%02X", &red, &green, &blue);

UIColor *color = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1];

I was looking for a simple solution and came up with this (not completely Objective-C, but works like a charm):

NSString *stringColor = @"#AABBCC";
NSUInteger red, green, blue;
sscanf([stringColor UTF8String], "#%02X%02X%02X", &red, &green, &blue);

UIColor *color = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1];
帅冕 2024-10-02 06:16:13

UIColor 有一个很好的类别,名为 "UIColor+Expanded" ,它有一个类方法用于获取来自 RGB 十六进制字符串的 UIColor:

使用起来很简单:

UIColor *myColor = [UIColor colorWithHexString:@"FF0000"];

此外,它还为 UIColor 添加了许多其他可能有用的实用程序。更多信息请参阅本文

There is a nice category for UIColor called "UIColor+Expanded" which has a class method for getting a UIColor from an RGB hex string:

It's simple to use:

UIColor *myColor = [UIColor colorWithHexString:@"FF0000"];

Plus it adds a lot of other potentially useful utilities to UIColor. More info is available in this article.

萌无敌 2024-10-02 06:16:13

很简单,只需访问此网站并输入您的十六进制值:http://www. corecoding.com/utilities/rgb-or-hex-to-float.php

Easy, Just go to this website and type in your hex value: http://www.corecoding.com/utilities/rgb-or-hex-to-float.php

西瓜 2024-10-02 06:16:13
+ (UIColor *)colorWithHexString:(NSString *)colorString
{
    colorString = [colorString stringByReplacingOccurrencesOfString:@"#" withString:@""];

    if (colorString.length == 3)
        colorString = [NSString stringWithFormat:@"%c%c%c%c%c%c",
        [colorString characterAtIndex:0], [colorString characterAtIndex:0],
        [colorString characterAtIndex:1], [colorString characterAtIndex:1],
        [colorString characterAtIndex:2], [colorString characterAtIndex:2]];

    if (colorString.length == 6)
    {
        int r, g, b;
        sscanf([colorString UTF8String], "%2x%2x%2x", &r, &g, &b);
        return [UIColor colorWithRed:(r/255.0) green:(g/255.0) blue:(b/255.0) alpha:1.0];
    }
    return nil;
}

对于格式 #123、123、#fff195、fff195

+ (UIColor *)colorWithHexValue:(int)hexValue
{
    float red   = ((hexValue & 0xFF0000) >> 16)/255.0;
    float green = ((hexValue & 0xFF00) >> 8)/255.0;
    float blue  = (hexValue & 0xFF)/255.0;
    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

对于格式 0xfff195

+ (UIColor *)colorWithHexString:(NSString *)colorString
{
    colorString = [colorString stringByReplacingOccurrencesOfString:@"#" withString:@""];

    if (colorString.length == 3)
        colorString = [NSString stringWithFormat:@"%c%c%c%c%c%c",
        [colorString characterAtIndex:0], [colorString characterAtIndex:0],
        [colorString characterAtIndex:1], [colorString characterAtIndex:1],
        [colorString characterAtIndex:2], [colorString characterAtIndex:2]];

    if (colorString.length == 6)
    {
        int r, g, b;
        sscanf([colorString UTF8String], "%2x%2x%2x", &r, &g, &b);
        return [UIColor colorWithRed:(r/255.0) green:(g/255.0) blue:(b/255.0) alpha:1.0];
    }
    return nil;
}

for format #123, 123, #fff195, fff195

+ (UIColor *)colorWithHexValue:(int)hexValue
{
    float red   = ((hexValue & 0xFF0000) >> 16)/255.0;
    float green = ((hexValue & 0xFF00) >> 8)/255.0;
    float blue  = (hexValue & 0xFF)/255.0;
    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

for format 0xfff195

Hello爱情风 2024-10-02 06:16:13

我发现的最简单的方法: 十六进制到 UIColor 转换器

只需键入不带 ' 的十六进制数字#',它返回 UIColor 代码。例如橙色 (#f77f00) 的代码是:

[UIColor colorWithRed:0.969 green:0.498 blue:0 alpha:1.0]

The easiest way that I found: Hex to UIColor Converter

Just type the hex number without '#', and it returns the UIColor code. For example the code for the orange color (#f77f00) is:

[UIColor colorWithRed:0.969 green:0.498 blue:0 alpha:1.0]
一江春梦 2024-10-02 06:16:13

我想我会将这六个字符分成三对,然后将其转换为十进制,然后除以 255 以获得每个颜色分量作为浮点数。

然后您可以将组件传递给:

[UIColor colorWithRed: green: blue: alpha:1];

I think I'd split the six characters into three pairs, then convert that to decimal, then divide that by 255 to get each color component as a float.

You can then pass the components to:

[UIColor colorWithRed: green: blue: alpha:1];
归途 2024-10-02 06:16:13

如果从 ObjectiveC 转换到 swift 对您来说很困难,那么 Swift 就是答案。目前它只接受不带 # 的字符串,但我相信您可以添加扫描仪方法来跳过它。

func stringToColor(stringColor: String) -> UIColor {
    var hexInt: UInt32 = 0
    let scanner = NSScanner(string: stringColor)
    scanner.scanHexInt(&hexInt)
    let color = UIColor(
        red: CGFloat((hexInt & 0xFF0000) >> 16)/255,
        green: CGFloat((hexInt & 0xFF00) >> 8)/255,
        blue: CGFloat((hexInt & 0xFF))/255,
        alpha: 1)

    return color
}

If converting from ObjectiveC to swift is hard for you, here's the answer with Swift. Currently it only takes strings without the #, but you can add a scanner method to skip it I believe.

func stringToColor(stringColor: String) -> UIColor {
    var hexInt: UInt32 = 0
    let scanner = NSScanner(string: stringColor)
    scanner.scanHexInt(&hexInt)
    let color = UIColor(
        red: CGFloat((hexInt & 0xFF0000) >> 16)/255,
        green: CGFloat((hexInt & 0xFF00) >> 8)/255,
        blue: CGFloat((hexInt & 0xFF))/255,
        alpha: 1)

    return color
}
む无字情书 2024-10-02 06:16:13

我创建了一个在线工具,可以在不方便使用自定义方法或插件时立即将任何十六进制代码转换为 Swift 和 Objective-C 的 UIColor 代码片段:https://iosref.com/uihex/

I created an online tool to instantly convert any hex code to a UIColor code snippet for Swift and Objective-C, for when it's inconvenient to use custom methods or plugins: https://iosref.com/uihex/

如痴如狂 2024-10-02 06:16:13

如果您不想编写上面的所有代码,您可以查看此站点: http://www.diovo.com/apps/rgb-to-uicolor-converter.html
从像这样的十六进制颜色:#FFFFFF,该网站将其转换为如下字符串:

UIColor *aColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1.000];

If you don't want to write all of this code above, you can check this site: http://www.diovo.com/apps/rgb-to-uicolor-converter.html
From an HEX color like this: #FFFFFF, the site convert it in a string like this:

UIColor *aColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1.000];

小帐篷 2024-10-02 06:16:13

不要忘记您可以选择将十六进制值转换为 RGB 并输入它们在界面生成器中。它将节省一些代码行。

rgb 滑块

Don't forget that you have the option to convert your hex values to RGB and enter them in the interface builder. It'll save some lines of code.

rgb sliders

那些过往 2024-10-02 06:16:13

我猜这有点晚了……但我在 WhiteHouse Github 存储库中找到了这个版本,它以一种非常优雅的方式实现了这一点:

+(UIColor *)colorFromRGBHexString:(NSString *)colorString {
    if(colorString.length == 7) {
        const char *colorUTF8String = [colorString UTF8String];
        int r, g, b;
        sscanf(colorUTF8String, "#%2x%2x%2x", &r, &g, &b);
        return [UIColor colorWithRed:(r / 255.0) green:(g / 255.0) blue:(b / 255.0) alpha:1.0];
    }    
    return nil;
}

GitHub 上 WHAppConfig.m 的源链接

Guess this is a bit late here... but I found this version in the WhiteHouse Github repo that does it in a pretty elegant way:

+(UIColor *)colorFromRGBHexString:(NSString *)colorString {
    if(colorString.length == 7) {
        const char *colorUTF8String = [colorString UTF8String];
        int r, g, b;
        sscanf(colorUTF8String, "#%2x%2x%2x", &r, &g, &b);
        return [UIColor colorWithRed:(r / 255.0) green:(g / 255.0) blue:(b / 255.0) alpha:1.0];
    }    
    return nil;
}

Source Link to their WHAppConfig.m on github

日裸衫吸 2024-10-02 06:16:13

我认为使用十六进制值有一种更简单的方法。
只需在文件顶部添加定义或引用头文件进行转换 (UIColorFromRGB)。您甚至可以添加固定十六进制颜色值的模板。

#define CLR_YELLOW_TEXT     0xf4dc89    // A Light Yellow text
#define CLR_GREEN_TEXT      0x008040    // Dark Green text for my buttons

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

然后直接使用十六进制值或您定义的十六进制值在代码中引用它。
例如...

[myButton1 setTitleColor:UIColorFromRGB(0xd02d2d) forState:UIControlStateNormal];
[myButton2 setTitleColor:UIColorFromRGB(CLR_GREEN_TEXT) forState:UIControlStateNormal];
[myButton3 setTitleColor:UIColorFromRGB(CLR_YELLOW_TEXT) forState:UIControlStateNormal];

(PS - 假设 Alpha 为 1.0,但它始终可以在定义中更改)。

享受。

I think there is an even easier way when using HEX values.
Just add a definition at the top of your file or reference a header file for the conversion (UIColorFromRGB). You can even add a template of fixed HEX color values.

#define CLR_YELLOW_TEXT     0xf4dc89    // A Light Yellow text
#define CLR_GREEN_TEXT      0x008040    // Dark Green text for my buttons

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

Then just reference it in your code using the HEX values directly or your defined hex values.
For example...

[myButton1 setTitleColor:UIColorFromRGB(0xd02d2d) forState:UIControlStateNormal];
[myButton2 setTitleColor:UIColorFromRGB(CLR_GREEN_TEXT) forState:UIControlStateNormal];
[myButton3 setTitleColor:UIColorFromRGB(CLR_YELLOW_TEXT) forState:UIControlStateNormal];

(PS - This assumes an Alpha of 1.0, but it can always be changed in the definition).

Enjoy.

醉城メ夜风 2024-10-02 06:16:13

我发现 cocoapod 库在使用“#RRGGBB”值创建 UIColor 方面非常有用。

pod 'UIColor-HexRGB'

I found a cocoapod library very useful in creating UIColor using "#RRGGBB" values.

pod 'UIColor-HexRGB'
淡淡的优雅 2024-10-02 06:16:13
+(UIColor*)colorWithHexString:(NSString*)hexString

{

NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

if ([cString length] < 6) return [UIColor grayColor];

if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];

if ([cString length] != 6) return  [UIColor grayColor];

NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];

range.location = 2;
NSString *gString = [cString substringWithRange:range];

range.location = 4;
NSString *bString = [cString substringWithRange:range];

unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];

return [UIColor colorWithRed:((float) r / 255.0f)
                       green:((float) g / 255.0f)
                        blue:((float) b / 255.0f)
                       alpha:1.0f];

}

+(UIColor*)colorWithHexString:(NSString*)hexString

{

NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

if ([cString length] < 6) return [UIColor grayColor];

if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];

if ([cString length] != 6) return  [UIColor grayColor];

NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];

range.location = 2;
NSString *gString = [cString substringWithRange:range];

range.location = 4;
NSString *bString = [cString substringWithRange:range];

unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];

return [UIColor colorWithRed:((float) r / 255.0f)
                       green:((float) g / 255.0f)
                        blue:((float) b / 255.0f)
                       alpha:1.0f];

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文