2012-01-17 36 views
1

我將顏色保存爲如何將顏色從字符串轉換回來?

colorObj.ToString()

然後,它是保存爲顏色[A = 255,R = 255,G = 255,B = 128]

現在如何將此字符串轉換回顏色?

我已經通過將RGB存儲在整數值中解決了問題,但該值爲負數,直到有人將其應用於代碼中才具有意義。這些[A = 255,R = 255,G = 255,B = 128] ARGB值更具可讀性。

+0

這樣看來,Color.ToString()根據.NET的版本返回不同的值。當前的文檔說它應該是一個十六進制值,而且我目前在.NET4中看到一個文本字符串,例如「Color [Yellow]」。你有不同的東西... – winwaed

回答

0

不那麼優雅的解決方案可能是拆分字符串並提取所需的值。例如:

var p = test.Split(new char[]{',',']'}); 

int A = Convert.ToInt32(p[0].Substring(p[0].IndexOf('=') + 1)); 
int R = Convert.ToInt32(p[1].Substring(p[1].IndexOf('=') + 1)); 
int G = Convert.ToInt32(p[2].Substring(p[2].IndexOf('=') + 1)); 
int B = Convert.ToInt32(p[3].Substring(p[3].IndexOf('=') + 1)); 

雖然這樣做一定有更好的方法,但這是首先想到的。

4

您可以將顏色存儲(並加載)爲HTML值,例如#FFDFD991。然後使用System.Drawing.ColorTranslator.ToHtml()System.Drawing.ColorTranslator.FromHtml()。另見this question

0

如果先轉換顏色通過 ColorTranslator.ToWin32(彩色win32Color)爲Int ,然後再轉換是詮釋爲String, 然後就通過 ColorTranslator.FromWin32將其轉換回詮釋和INT回顏色(顏色win32Color)

// 
Color CColor = Color.FromArgb(255, 20, 200, 100); 
int IColor; 
String SString; 
//from color to string  
IColor = ColorTranslator.ToWin32(CColor); 
SString = IColor.ToString(); 
//from string to color  
IColor = int.Parse(SString); 
CColor = ColorTranslator.FromWin32(IColor); 
1

打破Jontata的答案這就是我想出的。

它是Unity用戶的一個很好的解決方案,因爲它不需要繪圖庫。我只是做我自己的ToString函數,以便於轉換。

功能:

public static string colorToString(Color color){ 
    return color.r + "," + color.g + "," + color.b + "," + color.a; 
} 
public static Color stringToColor(string colorString){ 
    try{ 
     string[] colors = colorString.Split (','); 
     return new Color (float.Parse(colors [0]), float.Parse(colors [1]), float.Parse(colors [2]), float.Parse(colors [3])); 
    }catch{ 
     return Color.white; 
    } 
} 

用法:

Color red = new Color(1,0,0,1); 
string redStr = colorToString(red); 
Color convertedColor = stringToColor(redStr); //convertedColor will be red 
相關問題