【问题标题】:convert RGB int value to Hex format with 0x prefix in c#在c#中将RGB int值转换为带有0x前缀的Hex格式
【发布时间】:2014-11-27 10:06:24
【问题描述】:

我正在尝试使用以下代码将 RGB 值转换为 c# 中的十六进制格式:

int ColorValue = Color.FromName("mycolor").ToArgb();
string ColorHex = string.Format("{0:x6}", ColorValue);

colorHex 值喜欢这种格式ffffff00,但我需要像这样更改它:0x0000。我该怎么做?

最好的问候

我是 C# 表单应用程序的新手。

【问题讨论】:

    标签: c# hex rgb colordialog


    【解决方案1】:

    只需在格式字符串中自己添加0x 部分:

    // Local variable names to match normal conventions.
    
    // Although Color doesn't have ToRgb, we can just mask off the top 8 bits,
    // leaving RGB in the bottom 24 bits.
    int colorValue = Color.FromName("mycolor").ToArgb() & 0xffffff;
    string colorHex = string.Format("0x{0:x6}", colorValue);
    

    如果您想要大写十六进制值而不是小写,请改用"0x{0:X6}"

    【讨论】:

    • 谢谢乔恩。但我收到了这个错误:{System.FormatException:输入字符串的格式不正确。在 System.Text.StringBuilder.AppendFormat(IFormatProvider 提供程序,字符串格式,Object[] args)
    • @EA:呃,在哪里?这在我提供的代码中不会发生。如果您希望它是大写的(这是史蒂夫的回答所做的),您应该指定...
    • 这是我的错,但你的方法给了我这个结果:0xff008080
    • @EA:啊,我明白了。这很容易解决。请参阅我的编辑。您无需按照史蒂夫的回答手动进行算术运算。
    【解决方案2】:

    如果你只想要定义颜色的 RGB 部分的 3 个字节,你可以试试这个

        Color c = Color.FromName("mycolor");
        int ColorValue = (c.R * 65536) + (c.G * 256) + c.B;
        string ColorHex = string.Format("0x{0:X6}", ColorValue);
    

    【讨论】:

      猜你喜欢
      • 2022-08-17
      • 2015-01-17
      • 2016-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 2016-10-22
      相关资源
      最近更新 更多