【问题标题】:How to convert HEX RGB color codes to UIColor?如何将 HEX RGB 颜色代码转换为 UIColor?
【发布时间】:2025-02-17 00:05:02
【问题描述】:

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

【问题讨论】:

  • 如果您不想使用代码执行此操作,可以查看http://uicolor.io/。轻松将 HEX 和 RGB 转换为 Swift 和 Objective-C 的 UIColor,另外还有一个颜色选择器以防万一......
  • 只是更新 - http://uicolor.io/ 的 url 已更改 http://uicolor.xyz

标签: iphone uicolor


【解决方案1】:

In some code of mine,我使用了 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”等字符串。

【讨论】:

  • 我了解以下所有内容:((baseValue >> 24) & 0xFF)。 (我得到了 255.0f 的除法)。你能解释一下你是如何实现移位 24、16 和 8 位的吗?还有,你为什么要用 0xFF?谢谢你:)
  • 也许是正确的答案,但是否某种“有趣”听到了这个:“有没有简单的方法可以做到这一点?”我们需要写一本书来做到这一点。
  • 答案中的第一个链接已失效 (stackkit.com)。
【解决方案2】:

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

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

【讨论】:

  • 我希望 Apple 将其添加到他们的头文件中!没有理由不!
【解决方案3】:

我一直在寻找一个简单的解决方案并想出了这个(不完全是 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];

【讨论】:

  • 感谢您发布此内容,它对我来说非常有用!希望我能给你 +10 票。
  • 非常优雅的解决方案! +1
【解决方案4】:

有一个很好的 UIColor 类别,称为 "UIColor+Expanded",它有一个从 RGB 十六进制字符串中获取 UIColor 的类方法:

使用简单:

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

此外,它还为 UIColor 添加了许多其他可能有用的实用程序。更多信息请访问this article

【讨论】:

  • 它没有显示任何问题但它不起作用,我导入了 UIColor+Expanded.h 和 UIColor+Expanded.m。这是这条线。 self.navigationController.navigationBar.tintColor = [UIColor colorWithHexString:@"#555555"];
  • @Ravin455 你可能需要去掉那个 # 符号(如我原来的答案所示)。
  • 该类别的链接已损坏。
  • 试试 colorWithHexString 和 colorWithName from: github.com/phonegap/phonegap-plugins/blob/master/iPhone/…
  • 我更新了原帖指向UIColor+Expanded的新位置,也就是这里:github.com/erica/uicolor-utilities/tree/master/Color
【解决方案5】:

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

【讨论】:

  • 很棒的网站!谢谢
【解决方案6】:
+ (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

【讨论】:

    【解决方案7】:

    我找到的最简单的方法:Hex to UIColor Converter

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

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

    【讨论】:

    【解决方案8】:

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

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

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

    【讨论】:

      【解决方案9】:

      如果从 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
      }
      

      【讨论】:

        【解决方案10】:

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

        【讨论】:

          【解决方案11】:

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

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

          【讨论】:

            【解决方案12】:

            不要忘记您可以选择convert your hex values to RGB 并在界面构建器中输入它们。它会节省一些代码行。

            【讨论】:

              【解决方案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;
              }
              

              Source Link to their WHAppConfig.m on github

              【讨论】:

                【解决方案14】:

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

                #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,但始终可以在定义中更改)。

                享受吧。

                【讨论】:

                  【解决方案15】:

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

                  pod 'UIColor-HexRGB'
                  

                  【讨论】:

                    【解决方案16】:
                    +(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];
                    

                    }

                    【讨论】: