【问题标题】:Converting from RGB ints to Hex从 RGB 整数转换为十六进制
【发布时间】:2012-11-01 12:52:37
【问题描述】:

我拥有的是 R:255 G:181 B:178,我正在使用 C#(更具体地说,对于 WP8)

我想将此转换为十六进制数字以用作颜色(设置 WriteableBitmap 的像素颜色)。我正在做的事情如下:

int hex = (255 << 24) | ((byte)R << 16) | ((byte)G << 8) | ((Byte)B<<0);

但是当我这样做的时候,我只是变蓝了。

任何想法我做错了什么?

另外,要撤消这个,检查 RGB 值,我要去:

int r = ((byte)(hex >> 16)); // = 0
int g = ((byte)(hex >> 8)); // = 0
int b = ((byte)(hex >> 0)); // = 255

【问题讨论】:

  • 例如,CSS 中使用了十六进制格式的颜色。你是这个意思吗?例如白色 -> FFFFFF,蓝色 -> 0000FF?
  • 你是什么意思“只是变蓝” - 显示你的期望和你得到的......(即你当前的代码和值将给出 FFFFB5B2)
  • 我的意思是,我没有得到任何颜色:r:255, g:181, b:178 应该是(浅粉色),我只得到 0000FF(蓝色)
  • 您是否尝试将类型转换更改为int 而不是byte?例如:int hex = (255 &lt;&lt; 24) | ((int)R &lt;&lt; 16) | ((int)G &lt;&lt; 8) | ((int)B&lt;&lt;0);
  • 字节应该没问题...((255 &lt;&lt; 24) | ((byte)255 &lt;&lt; 16) | ((byte)181 &lt;&lt; 8) | ((Byte)178&lt;&lt;0)).ToString("X") not 是否给出 0000FF。

标签: c# bitmap bit-shift


【解决方案1】:

试试下面的:

using System.Drawing;
Color myColor = Color.FromArgb(255, 181, 178);
string hex = myColor.R.ToString("X2") + myColor.G.ToString("X2") + myColor.B.ToString("X2");

【讨论】:

  • 或者只在字节上使用 ToString("X2") 部分
  • 您说“将其转换为十六进制数字”,但 HEX 不是数字,它是用于表示数字的字符串。
  • 哦..对不起,我猜十六进制只是为了让用户更容易看到。但是位图的像素数组是一个 int[],所以我需要这个数字是一个 int(即弄清楚如何添加 R、G、B)
  • WriteableBitmap 的哪个属性/方法需要这个 int?
  • 我只是想设置 WriteableBitmap.Pixel 数组项...我设法弄明白了(我认为..)。根据上面的评论,我刚刚更改了括号;)
【解决方案2】:

使用字符串插值,可以写成:

$"{r:X2}{g:X2}{b:X2}"

【讨论】:

    【解决方案3】:

    您可以使用较短的字符串格式来避免字符串连接。

    string.Format("{0:X2}{1:X2}{2:X2}", r, g, b)
    

    【讨论】:

      【解决方案4】:

      问候人类,

      //Red Value
      int integerRedValue = 0;
      //Green Value
      int integerGreenValue = 0;
      //Blue Value
      int integerBlueValue  = 0;
      
      string hexValue = integerRedValue.ToString("X2") + integerGreenValue.ToString("X2") + integerBlueValue.ToString("X2");
      

      【讨论】:

        【解决方案5】:

        您可以为此使用ColorHelper 库:

        using ColorHelper;
        RGB rgb = new RGB(100, 0, 100);
        HEX hex = ColorConverter.RgbToHex(rgb);
        

        【讨论】:

          猜你喜欢
          • 2020-01-04
          • 2021-03-22
          • 2010-10-16
          • 1970-01-01
          • 2016-03-09
          • 2020-11-14
          相关资源
          最近更新 更多