SvgColourConverter.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. #pragma warning disable
  9. namespace Svg
  10. {
  11. /// <summary>
  12. /// Converts string representations of colours into <see cref="Color"/> objects.
  13. /// </summary>
  14. public class SvgColourConverter : ColorConverter
  15. {
  16. /// <summary>
  17. /// Converts the given object to the converter's native type.
  18. /// </summary>
  19. /// <param name="context">A <see cref="T:System.ComponentModel.TypeDescriptor"/> that provides a format context. You can use this object to get additional information about the environment from which this converter is being invoked.</param>
  20. /// <param name="culture">A <see cref="T:System.Globalization.CultureInfo"/> that specifies the culture to represent the color.</param>
  21. /// <param name="value">The object to convert.</param>
  22. /// <returns>
  23. /// An <see cref="T:System.Object"/> representing the converted value.
  24. /// </returns>
  25. /// <exception cref="T:System.ArgumentException">The conversion cannot be performed.</exception>
  26. /// <PermissionSet>
  27. /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/>
  28. /// </PermissionSet>
  29. public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
  30. {
  31. string colour = value as string;
  32. if (colour != null)
  33. {
  34. var oldCulture = Thread.CurrentThread.CurrentCulture;
  35. try
  36. {
  37. Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
  38. colour = colour.Trim();
  39. if (colour.StartsWith("rgb"))
  40. {
  41. try
  42. {
  43. int start = colour.IndexOf("(") + 1;
  44. //get the values from the RGB string
  45. string[] values = colour.Substring(start, colour.IndexOf(")") - start).Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
  46. //determine the alpha value if this is an RGBA (it will be the 4th value if there is one)
  47. int alphaValue = 255;
  48. if (values.Length > 3)
  49. {
  50. //the alpha portion of the rgba is not an int 0-255 it is a decimal between 0 and 1
  51. //so we have to determine the corosponding byte value
  52. var alphastring = values[3];
  53. if (alphastring.StartsWith("."))
  54. {
  55. alphastring = "0" + alphastring;
  56. }
  57. var alphaDecimal = decimal.Parse(alphastring);
  58. if (alphaDecimal <= 1)
  59. {
  60. alphaValue = (int)Math.Round(alphaDecimal * 255);
  61. }
  62. else
  63. {
  64. alphaValue = (int)Math.Round(alphaDecimal);
  65. }
  66. }
  67. Color colorpart;
  68. if (values[0].Trim().EndsWith("%"))
  69. {
  70. colorpart = System.Drawing.Color.FromArgb(alphaValue, (int)Math.Round(255 * float.Parse(values[0].Trim().TrimEnd('%')) / 100f),
  71. (int)Math.Round(255 * float.Parse(values[1].Trim().TrimEnd('%')) / 100f),
  72. (int)Math.Round(255 * float.Parse(values[2].Trim().TrimEnd('%')) / 100f));
  73. }
  74. else
  75. {
  76. colorpart = System.Drawing.Color.FromArgb(alphaValue, int.Parse(values[0]), int.Parse(values[1]), int.Parse(values[2]));
  77. }
  78. return colorpart;
  79. }
  80. catch
  81. {
  82. throw new SvgException("Colour is in an invalid format: '" + colour + "'");
  83. }
  84. }
  85. // HSL support
  86. else if (colour.StartsWith("hsl"))
  87. {
  88. try
  89. {
  90. int start = colour.IndexOf("(") + 1;
  91. //get the values from the RGB string
  92. string[] values = colour.Substring(start, colour.IndexOf(")") - start).Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
  93. if (values[1].EndsWith("%"))
  94. {
  95. values[1] = values[1].TrimEnd('%');
  96. }
  97. if (values[2].EndsWith("%"))
  98. {
  99. values[2] = values[2].TrimEnd('%');
  100. }
  101. // Get the HSL values in a range from 0 to 1.
  102. double h = double.Parse(values[0]) / 360.0;
  103. double s = double.Parse(values[1]) / 100.0;
  104. double l = double.Parse(values[2]) / 100.0;
  105. // Convert the HSL color to an RGB color
  106. Color colorpart = Hsl2Rgb(h, s, l);
  107. return colorpart;
  108. }
  109. catch
  110. {
  111. throw new SvgException("Colour is in an invalid format: '" + colour + "'");
  112. }
  113. }
  114. else if (colour.StartsWith("#") && colour.Length == 4)
  115. {
  116. colour = string.Format(culture, "#{0}{0}{1}{1}{2}{2}", colour[1], colour[2], colour[3]);
  117. return base.ConvertFrom(context, culture, colour);
  118. }
  119. switch (colour.ToLowerInvariant())
  120. {
  121. case "activeborder": return SystemColors.ActiveBorder;
  122. case "activecaption": return SystemColors.ActiveCaption;
  123. case "appworkspace": return SystemColors.AppWorkspace;
  124. case "background": return SystemColors.Desktop;
  125. case "buttonface": return SystemColors.Control;
  126. case "buttonhighlight": return SystemColors.ControlLightLight;
  127. case "buttonshadow": return SystemColors.ControlDark;
  128. case "buttontext": return SystemColors.ControlText;
  129. case "captiontext": return SystemColors.ActiveCaptionText;
  130. case "graytext": return SystemColors.GrayText;
  131. case "highlight": return SystemColors.Highlight;
  132. case "highlighttext": return SystemColors.HighlightText;
  133. case "inactiveborder": return SystemColors.InactiveBorder;
  134. case "inactivecaption": return SystemColors.InactiveCaption;
  135. case "inactivecaptiontext": return SystemColors.InactiveCaptionText;
  136. case "infobackground": return SystemColors.Info;
  137. case "infotext": return SystemColors.InfoText;
  138. case "menu": return SystemColors.Menu;
  139. case "menutext": return SystemColors.MenuText;
  140. case "scrollbar": return SystemColors.ScrollBar;
  141. case "threeddarkshadow": return SystemColors.ControlDarkDark;
  142. case "threedface": return SystemColors.Control;
  143. case "threedhighlight": return SystemColors.ControlLight;
  144. case "threedlightshadow": return SystemColors.ControlLightLight;
  145. case "window": return SystemColors.Window;
  146. case "windowframe": return SystemColors.WindowFrame;
  147. case "windowtext": return SystemColors.WindowText;
  148. }
  149. }
  150. finally
  151. {
  152. // Make sure to set back the old culture even an error occurred.
  153. Thread.CurrentThread.CurrentCulture = oldCulture;
  154. }
  155. }
  156. return base.ConvertFrom(context, culture, value);
  157. }
  158. public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType)
  159. {
  160. if (sourceType == typeof(string))
  161. {
  162. return true;
  163. }
  164. return base.CanConvertFrom(context, sourceType);
  165. }
  166. public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, Type destinationType)
  167. {
  168. if (destinationType == typeof(string))
  169. {
  170. return true;
  171. }
  172. return base.CanConvertTo(context, destinationType);
  173. }
  174. public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
  175. {
  176. if (destinationType == typeof(string))
  177. {
  178. var colour = (Color)value;
  179. return "#" + colour.R.ToString("X2", null) + colour.G.ToString("X2", null) + colour.B.ToString("X2", null);
  180. }
  181. return base.ConvertTo(context, culture, value, destinationType);
  182. }
  183. /// <summary>
  184. /// Converts HSL color (with HSL specified from 0 to 1) to RGB color.
  185. /// Taken from http://www.geekymonkey.com/Programming/CSharp/RGB2HSL_HSL2RGB.htm
  186. /// </summary>
  187. /// <param name="h"></param>
  188. /// <param name="sl"></param>
  189. /// <param name="l"></param>
  190. /// <returns></returns>
  191. private static Color Hsl2Rgb(double h, double sl, double l)
  192. {
  193. double r = l; // default to gray
  194. double g = l;
  195. double b = l;
  196. double v = (l <= 0.5) ? (l * (1.0 + sl)) : (l + sl - l * sl);
  197. if (v > 0)
  198. {
  199. double m;
  200. double sv;
  201. int sextant;
  202. double fract, vsf, mid1, mid2;
  203. m = l + l - v;
  204. sv = (v - m) / v;
  205. h *= 6.0;
  206. sextant = (int)h;
  207. fract = h - sextant;
  208. vsf = v * sv * fract;
  209. mid1 = m + vsf;
  210. mid2 = v - vsf;
  211. switch (sextant)
  212. {
  213. case 0:
  214. r = v;
  215. g = mid1;
  216. b = m;
  217. break;
  218. case 1:
  219. r = mid2;
  220. g = v;
  221. b = m;
  222. break;
  223. case 2:
  224. r = m;
  225. g = v;
  226. b = mid1;
  227. break;
  228. case 3:
  229. r = m;
  230. g = mid2;
  231. b = v;
  232. break;
  233. case 4:
  234. r = mid1;
  235. g = m;
  236. b = v;
  237. break;
  238. case 5:
  239. r = v;
  240. g = m;
  241. b = mid2;
  242. break;
  243. }
  244. }
  245. Color rgb = Color.FromArgb((int)Math.Round(r * 255.0), (int)Math.Round(g * 255.0), (int)Math.Round(b * 255.0));
  246. return rgb;
  247. }
  248. }
  249. }
  250. #pragma warning restore