Animation.cs 6.3 KB

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