c# - 如何使用 C# 在 Windows 控制台应用程序中创建 ASCII 动画?

标签 c# animation console-application ascii-art

我希望它能像这个很棒的 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/

相关文章:

c# - 文本框属性

c# - 如何将元素绑定(bind)到属于控件根元素的属性?

c# - 为什么我的 C# 代码比我的 C 代码快?

objective-c - 在 iOS 的 Objective-C 中创建带有完成 block 的可中断动画?

android - 如何从命令行启动 Android 模拟器?

c# - 在设计器中设置 mySQL 参数查询

android - 如何更改警报对话框的位置

javascript - 单击按钮后停止动画

C++ GUI 和控制台应用程序

c# - 如何将 Unicode 字符写入控制台?