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

时间:2011-03-29 18:43:43

标签: c# .net wpf

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

6 个答案:

答案 0 :(得分:6)

试试这个

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

答案 1 :(得分:6)

int red = 255;
int green = 255;
int blue = 255;

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

答案 2 :(得分:3)

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

答案 3 :(得分:1)

请找到以下扩展方法:

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

答案 4 :(得分:0)

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

答案 5 :(得分:-1)

我做的是以下内容:

    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
    }

0