2017-04-25 22 views
0

我需要從System.Drawing.Color.FromKnownName將System.Drawing.Color.Red轉換爲「紅色」或「紅色」的相反功能。System.Drawing.Color ToKnownName

爲了提供示例代碼:

private static XElement BlipToXml(Blip blip) 
    { 
     var tmp = new XElement("Blip", 
      new XAttribute("X", blip.Position.X), 
      new XAttribute("Y", blip.Position.Y), 
      new XAttribute("Z", blip.Position.Z), 
      new XAttribute("color", blip.Color.), <-- This is where i need the ToKnownName 
      new XAttribute("transparency", blip.Alpha), 
      new XAttribute("sprite", blip.Sprite)); 
     tmp.SetValue(blip.Name); 
     return tmp; 
    } 
    private static Blip XmlToBlip(XElement xml) 
    { 
     var x = float.Parse(xml.Attribute("X").ToString()); 
     var y = float.Parse(xml.Attribute("Y").ToString()); 
     var z = float.Parse(xml.Attribute("Z").ToString()); 
     var coords = new Vector3(x,y,z); 
     var tmp = new Blip(coords); 
     tmp.Color = System.Drawing.Color.FromName(xml.Attribute("color").ToString()); 
     tmp.Alpha = float.Parse(xml.Attribute("transparency").ToString()); 
     tmp.Sprite = (BlipSprite)Enum.Parse(typeof(BlipSprite), xml.Attribute("sprite").ToString()); 
     tmp.Name = xml.Value; 
     return tmp; 
    } 
+0

我不知道爲什麼'(KnownColor)Enum.Parse(typeof運算(KnownColor),blip.Color.ToKnownColor()'這裏行不通。 – Bluscream

回答

1

此方法使用反射來檢查上Color類的預定義的顏色,並將它們與針對傳遞作爲參數的顏色。

private static String GetColorName(Color color) 
{ 
    var predefined = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static); 
    var match = (from p in predefined where ((Color)p.GetValue(null, null)).ToArgb() == color.ToArgb() select (Color)p.GetValue(null, null)); 
    if (match.Any()) 
     return match.First().Name; 
    return String.Empty; 
} 
+0

謝謝,但https://i.imgur.com/ xGT2lXA.png – Bluscream

+0

@Bluscream使用System.Reflection添加; –

+0

工作正常,謝謝你先生:) – Bluscream

相關問題