Animation.cs 6.2 KB

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