Animation.cs 8.7 KB

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