请问有人能告诉我如何在C#中将三个int值 r,g,b
转换为字符串颜色(十六进制值)吗?
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;
System.Windows.Media.Color
没有Name的定义,但是System.Drawing.Color
有。 - StecyaRGB 转 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
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
}
O
string color = string.Format("#{0:X}{1:X}{2:X}", r,g,b);"
。 - StecyaX2
而不是X:2
。这是完整的代码:string.Format("${0:X2}{1:X2}{2:X2}", r, g, b)
- jep