2011-03-29 87 views

回答

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

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

alpha值呢? – Stecya 2011-03-29 18:47:07

+1

取決於你的格式:即ARGB將簡單地把你的alpha.ToString(「X」)放在紅色的前面等等。重點在於ToString(「X」)方法將返回一個十六進制格式的整數值。 – Tejs 2011-03-29 18:48:26

+3

比你的例子更好地寫'string color = string.Format(「#{0:X} {1:X} {2:X}」,r,g,b);' – Stecya 2011-03-29 18:51:37

6

試試這個

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

我只是想指出的是,0之間進行切換。當未從Argb創建Color時,Name屬性將不會給出十六進制值。 (比如Color.Red.Name會返回「Red」值) – HABJAN 2011-03-29 18:57:16

+0

是的,我知道但是saikamesh說他想從RGB值中得到字符串 – Stecya 2011-03-29 18:59:10

+0

他說他想要「hexa值」。 – 2011-03-29 19:18:44

3

RGB到十六進制:

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

十六進制到RGB:

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

給出錯誤:'System.Windows.Media.Color'不包含'ToArgb'的定義,並且沒有找到接受'System.Windows.Media.Color'類型的第一個參數的擴展方法'ToArgb'(你是否缺少using指令或程序集引用?) – saikamesh 2011-03-30 04:28:17

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")); 
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); 
-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再到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 
    } 

Ø