Animation.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. using System;
  2. using System.IO;
  3. using System.Reflection;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using SixLabors.ImageSharp;
  7. using SixLabors.ImageSharp.PixelFormats;
  8. using SixLabors.ImageSharp.Processing;
  9. using Terminal.Gui;
  10. namespace UICatalog.Scenarios;
  11. [ScenarioMetadata ("Animation", "Demonstration of how to render animated images with threading.")]
  12. [ScenarioCategory ("Threading")]
  13. [ScenarioCategory ("Drawing")]
  14. public class Animation : Scenario
  15. {
  16. private bool _isDisposed;
  17. public override void Setup ()
  18. {
  19. base.Setup ();
  20. var imageView = new ImageView { Width = Dim.Fill (), Height = Dim.Fill () - 2 };
  21. Win.Add (imageView);
  22. var lbl = new Label { Y = Pos.AnchorEnd (2), Text = "Image by Wikiscient" };
  23. Win.Add (lbl);
  24. var lbl2 = new Label
  25. {
  26. Y = Pos.AnchorEnd (1), Text = "https://commons.wikimedia.org/wiki/File:Spinning_globe.gif"
  27. };
  28. Win.Add (lbl2);
  29. DirectoryInfo dir;
  30. string assemblyLocation = Assembly.GetExecutingAssembly ().Location;
  31. if (!string.IsNullOrEmpty (assemblyLocation))
  32. {
  33. dir = new DirectoryInfo (Path.GetDirectoryName (assemblyLocation));
  34. }
  35. else
  36. {
  37. dir = new DirectoryInfo (AppContext.BaseDirectory);
  38. }
  39. var f = new FileInfo (
  40. Path.Combine (dir.FullName, "Scenarios", "Spinning_globe_dark_small.gif")
  41. );
  42. if (!f.Exists)
  43. {
  44. MessageBox.ErrorQuery ("Could not find gif", "Could not find " + f.FullName, "Ok");
  45. return;
  46. }
  47. imageView.SetImage (Image.Load<Rgba32> (File.ReadAllBytes (f.FullName)));
  48. Task.Run (
  49. () =>
  50. {
  51. while (!_isDisposed)
  52. {
  53. // When updating from a Thread/Task always use Invoke
  54. Application.Invoke (
  55. () =>
  56. {
  57. imageView.NextFrame ();
  58. imageView.SetNeedsDisplay ();
  59. }
  60. );
  61. Task.Delay (100).Wait ();
  62. }
  63. }
  64. );
  65. }
  66. protected override void Dispose (bool disposing)
  67. {
  68. _isDisposed = true;
  69. base.Dispose (disposing);
  70. }
  71. // This is a C# port of https://github.com/andraaspar/bitmap-to-braille by Andraaspar
  72. /// <summary>Renders an image as unicode Braille.</summary>
  73. public class BitmapToBraille
  74. {
  75. public const int CHAR_HEIGHT = 4;
  76. public const int CHAR_WIDTH = 2;
  77. private const string CHARS =
  78. " ⠁⠂⠃⠄⠅⠆⠇⡀⡁⡂⡃⡄⡅⡆⡇⠈⠉⠊⠋⠌⠍⠎⠏⡈⡉⡊⡋⡌⡍⡎⡏⠐⠑⠒⠓⠔⠕⠖⠗⡐⡑⡒⡓⡔⡕⡖⡗⠘⠙⠚⠛⠜⠝⠞⠟⡘⡙⡚⡛⡜⡝⡞⡟⠠⠡⠢⠣⠤⠥⠦⠧⡠⡡⡢⡣⡤⡥⡦⡧⠨⠩⠪⠫⠬⠭⠮⠯⡨⡩⡪⡫⡬⡭⡮⡯⠰⠱⠲⠳⠴⠵⠶⠷⡰⡱⡲⡳⡴⡵⡶⡷⠸⠹⠺⠻⠼⠽⠾⠿⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⣀⣁⣂⣃⣄⣅⣆⣇⢈⢉⢊⢋⢌⢍⢎⢏⣈⣉⣊⣋⣌⣍⣎⣏⢐⢑⢒⢓⢔⢕⢖⢗⣐⣑⣒⣓⣔⣕⣖⣗⢘⢙⢚⢛⢜⢝⢞⢟⣘⣙⣚⣛⣜⣝⣞⣟⢠⢡⢢⢣⢤⢥⢦⢧⣠⣡⣢⣣⣤⣥⣦⣧⢨⢩⢪⢫⢬⢭⢮⢯⣨⣩⣪⣫⣬⣭⣮⣯⢰⢱⢲⢳⢴⢵⢶⢷⣰⣱⣲⣳⣴⣵⣶⣷⢸⢹⢺⢻⢼⢽⢾⢿⣸⣹⣺⣻⣼⣽⣾⣿";
  79. public BitmapToBraille (int widthPixels, int heightPixels, Func<int, int, bool> pixelIsLit)
  80. {
  81. WidthPixels = widthPixels;
  82. HeightPixels = heightPixels;
  83. PixelIsLit = pixelIsLit;
  84. }
  85. public int HeightPixels { get; }
  86. public Func<int, int, bool> PixelIsLit { get; }
  87. public int WidthPixels { get; }
  88. public string GenerateImage ()
  89. {
  90. var imageHeightChars = (int)Math.Ceiling ((double)HeightPixels / CHAR_HEIGHT);
  91. var imageWidthChars = (int)Math.Ceiling ((double)WidthPixels / CHAR_WIDTH);
  92. var result = new StringBuilder ();
  93. for (var y = 0; y < imageHeightChars; y++)
  94. {
  95. for (var x = 0; x < imageWidthChars; x++)
  96. {
  97. int baseX = x * CHAR_WIDTH;
  98. int baseY = y * CHAR_HEIGHT;
  99. var charIndex = 0;
  100. var value = 1;
  101. for (var charX = 0; charX < CHAR_WIDTH; charX++)
  102. {
  103. for (var charY = 0; charY < CHAR_HEIGHT; charY++)
  104. {
  105. int bitmapX = baseX + charX;
  106. int bitmapY = baseY + charY;
  107. bool pixelExists = bitmapX < WidthPixels && bitmapY < HeightPixels;
  108. if (pixelExists && PixelIsLit (bitmapX, bitmapY))
  109. {
  110. charIndex += value;
  111. }
  112. value *= 2;
  113. }
  114. }
  115. result.Append (CHARS [charIndex]);
  116. }
  117. result.Append ('\n');
  118. }
  119. return result.ToString ().TrimEnd ();
  120. }
  121. }
  122. private class ImageView : View
  123. {
  124. private string [] brailleCache;
  125. private int currentFrame;
  126. private int frameCount;
  127. private Image<Rgba32> [] fullResImages;
  128. private Image<Rgba32> [] matchSizes;
  129. private Rectangle oldSize = Rectangle.Empty;
  130. public void NextFrame () { currentFrame = (currentFrame + 1) % frameCount; }
  131. public override void OnDrawContent (Rectangle contentArea)
  132. {
  133. base.OnDrawContent (contentArea);
  134. if (oldSize != Viewport)
  135. {
  136. // Invalidate cached images now size has changed
  137. matchSizes = new Image<Rgba32> [frameCount];
  138. brailleCache = new string [frameCount];
  139. oldSize = Viewport;
  140. }
  141. Image<Rgba32> imgScaled = matchSizes [currentFrame];
  142. string braille = brailleCache [currentFrame];
  143. if (imgScaled == null)
  144. {
  145. Image<Rgba32> imgFull = fullResImages [currentFrame];
  146. // keep aspect ratio
  147. int newSize = Math.Min (Viewport.Width, Viewport.Height);
  148. // generate one
  149. matchSizes [currentFrame] = imgScaled = imgFull.Clone (
  150. x => x.Resize (
  151. newSize * BitmapToBraille.CHAR_HEIGHT,
  152. newSize * BitmapToBraille.CHAR_HEIGHT
  153. )
  154. );
  155. }
  156. if (braille == null)
  157. {
  158. brailleCache [currentFrame] = braille = GetBraille (matchSizes [currentFrame]);
  159. }
  160. string [] lines = braille.Split ('\n');
  161. for (var y = 0; y < lines.Length; y++)
  162. {
  163. string line = lines [y];
  164. for (var x = 0; x < line.Length; x++)
  165. {
  166. AddRune (x, y, (Rune)line [x]);
  167. }
  168. }
  169. }
  170. internal void SetImage (Image<Rgba32> image)
  171. {
  172. frameCount = image.Frames.Count;
  173. fullResImages = new Image<Rgba32> [frameCount];
  174. matchSizes = new Image<Rgba32> [frameCount];
  175. brailleCache = new string [frameCount];
  176. for (var i = 0; i < frameCount - 1; i++)
  177. {
  178. fullResImages [i] = image.Frames.ExportFrame (0);
  179. }
  180. fullResImages [frameCount - 1] = image;
  181. SetNeedsDisplay ();
  182. }
  183. private string GetBraille (Image<Rgba32> img)
  184. {
  185. var braille = new BitmapToBraille (
  186. img.Width,
  187. img.Height,
  188. (x, y) => IsLit (img, x, y)
  189. );
  190. return braille.GenerateImage ();
  191. }
  192. private bool IsLit (Image<Rgba32> img, int x, int y)
  193. {
  194. Rgba32 rgb = img [x, y];
  195. return rgb.R + rgb.G + rgb.B > 50;
  196. }
  197. }
  198. }