我希望它能像这个很棒的 Linux 命令一样显示不闪烁的动画; sl
http://www.youtube.com/watch?v=9GyMZKWjcYU
我会很感激一个小而愚蠢的例子,比如……一只苍蝇。
谢谢!
最佳答案
只需使用Console.SetCursorPosition
将光标移动到某个位置,然后Console.Write
一个字符。在每一帧之前,您必须通过用空格覆盖它来删除前一帧。这是我刚刚构建的一个小示例:
class Program
{
static void Main(string[] args)
{
char[] chars = new char[] { '.', '-', '+', '^', '°', '*' };
for (int i = 0; ; i++)
{
if (i != 0)
{
// Delete the previous char by setting it to a space
Console.SetCursorPosition(6 - (i-1) % 6 - 1, Console.CursorTop);
Console.Write(" ");
}
// Write the new char
Console.SetCursorPosition(6 - i % 6 - 1, Console.CursorTop);
Console.Write(chars[i % 6]);
System.Threading.Thread.Sleep(100);
}
}
}
例如,您可以获取动画 gif,从中提取所有单帧/图像(参见如何操作 here ),应用 ASCII 转换(如何操作在 here 中描述)并打印这些逐帧像上面的代码示例。
更新
只是为了好玩,我实现了我刚才描述的内容。尝试将 @"C:\some_animated_gif.gif.gif"
替换为某些(不是很大的)动画 gif 的路径。例如,从 here 获取 AJAX 加载器 gif。 .
class Program
{
static void Main(string[] args)
{
Image image = Image.FromFile(@"C:\some_animated_gif.gif");
FrameDimension dimension = new FrameDimension(
image.FrameDimensionsList[0]);
int frameCount = image.GetFrameCount(dimension);
StringBuilder sb;
// Remember cursor position
int left = Console.WindowLeft, top = Console.WindowTop;
char[] chars = { '#', '#', '@', '%', '=', '+',
'*', ':', '-', '.', ' ' };
for (int i = 0; ; i = (i + 1) % frameCount)
{
sb = new StringBuilder();
image.SelectActiveFrame(dimension, i);
for (int h = 0; h < image.Height; h++)
{
for (int w = 0; w < image.Width; w++)
{
Color cl = ((Bitmap)image).GetPixel(w, h);
int gray = (cl.R + cl.G + cl.B) / 3;
int index = (gray * (chars.Length - 1)) / 255;
sb.Append(chars[index]);
}
sb.Append('\n');
}
Console.SetCursorPosition(left, top);
Console.Write(sb.ToString());
System.Threading.Thread.Sleep(100);
}
}
}
关于c# - 如何使用 C# 在 Windows 控制台应用程序中创建 ASCII 动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2725529/