如何将RGB int值转换为字符串颜色

任何人都可以告诉我如何将三个int vales r, g, b转换为C#中的字符串颜色(hexa值)

 int red = 255; int green = 255; int blue = 255; string theHexColor = "#" + red.ToString("X2") + green.ToString("X2") + blue.ToString("X2"); 

试试这个

  string s = Color.FromArgb(255, 143, 143, 143).Name; 

Rgb到Hex:

 string hexColor = string.Format("0x{0:X8}", Color.FromArgb(r, g, b).ToArgb()); 

hex到Rgb:

 int rgbColor = int.Parse("FF", System.Globalization.NumberStyles.AllowHexSpecifier); 

请找到以下扩展方法:

 public static class ColorExtensions { public static string ToRgb(this int argb) { var r = ((argb >> 16) & 0xff); var g = ((argb >> 8) & 0xff); var b = (argb & 0xff); return string.Format("{0:X2}{1:X2}{2:X2}", r, g, b); } } 

在这里你是用法:

  int colorBlack = 0x000000; int colorWhite = 0xffffff; Assert.That(colorBlack.ToRgb(), Is.EqualTo("000000")); Assert.That(colorWhite.ToRgb(), Is.EqualTo("FFFFFF")); 

为PowerPoint形状对象的Fill.ForeColor.RGB成员解决此问题,我发现RGB值实际上是BGR(蓝色,绿色,红色),因此C#PowerPoint插件的解决方案,将Fill.ForeColor.RGB转换为字符串是:

 string strColor = ""; var b = ((shpTemp.Fill.ForeColor.RGB >> 16) & 0xff); var g = ((shpTemp.Fill.ForeColor.RGB >> 8) & 0xff); var r = (shpTemp.Fill.ForeColor.RGB & 0xff); strColor = string.Format("{0:X2}{1:X2}{2:X2}", r, g, b); 

我做的是以下内容:

  int reducedRed = getRed(long color)/128; // this gives you a number 1 or 0. int reducedGreen = getGreen(long color)/128; // same thing for the green value; int reducedBlue = getBlue(long color)/128; //same thing for blue int reducedColor = reducedBlue + reducedGreen*2 + reducedRed*4 ; // reduced Color is a number between 0 -7 

一旦你有reducedColor然后执行0到7之间的切换。

  switch(reducedColor){ case 0: return "000000"; // corresponds to Black case 1: return “0000FF"; // corresponds to Blue case 2: return "00FF00"; // corresponds to Green case 3: return "00FFFF"; // corresponds to Cyan case 4: return “FF0000"; // corresponds to Red case 5: return "FF00FF"; //corresponds to Purple case 6: return "FFFF00"; //corresponds to Yellow case 7: return “FFFFFF"; //corresponds to White } 

Ø