Animation.cs 6.3 KB

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