2017-04-25 3 views
0

System.Drawing.Color.Red를 "Red"또는 "red"로 변환하는 System.Drawing.Color.FromKnownName에서 반대 기능이 필요합니다. 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