如何在控制台应用程序中绘制一个矩形?

6
我需要在C#控制台应用程序中使用扩展ASCII绘制一个带有数字的矩形。我该如何做?
这是为了演示。

可能是Console.Write() - 显示扩展ASCII字符?的重复问题。 - Josh Lee
C#不使用ASCII,无论是扩展还是其他。 - David Heffernan
5个回答

13
public class ConsoleRectangle
{
    private int hWidth;
    private int hHeight;
    private Point hLocation;
    private ConsoleColor hBorderColor;

    public ConsoleRectangle(int width, int height, Point location, ConsoleColor borderColor)
    {
        hWidth = width;
        hHeight = height;
        hLocation = location;
        hBorderColor = borderColor;
    }

    public Point Location
    {
        get { return hLocation; }
        set { hLocation = value; }
    }

    public int Width
    {
        get { return hWidth; }
        set { hWidth = value; }
    }

    public int Height
    {
        get { return hHeight; }
        set { hHeight = value; }
    }

    public ConsoleColor BorderColor
    {
        get { return hBorderColor; }
        set { hBorderColor = value; }
    }

    public void Draw()
    {
        string s = "╔";
        string space = "";
        string temp = "";
        for (int i = 0; i < Width; i++)
        {
            space += " ";
            s += "═";
        }

        for (int j = 0; j < Location.X ; j++)
            temp += " ";

        s += "╗" + "\n";

        for (int i = 0; i < Height; i++)
            s += temp + "║" + space + "║" + "\n";

        s += temp + "╚";
        for (int i = 0; i < Width; i++)
            s += "═";

        s += "╝" + "\n";

        Console.ForegroundColor = BorderColor;
        Console.CursorTop = hLocation.Y;
        Console.CursorLeft = hLocation.X;
        Console.Write(s);
        Console.ResetColor();
    }
}

如果我需要在矩形内绘制数字,你如何使用它? - user712923
如果你正在将一个框绘制在整个控制台区域周围,那么需要将宽度和高度减少两个单位(因为每个维度中的第一个和最后一个字符不可用/不可得,被角落字符占据)。 - Agi Hammerthief
有没有办法修改这个程序,使你可以画两个矩形(一个在另一个内部)?由于间隔的原因,第二个矩形覆盖了第一个矩形的左水平线。 - Mike
如果您想复制/粘贴:╔ ═ ╗ ╚ ╝ - Alex K.
1
@Alex,你忘记了 - IC_

5
这是一个针对String类型的扩展方法,可以在给定字符串周围绘制一个控制台框。支持多行。
例如: string tmp = "some value"; Console.Write(tmp.DrawInConsoleBox());
        public static string DrawInConsoleBox(this string s)
        {
            string ulCorner = "╔";
            string llCorner = "╚";
            string urCorner = "╗";
            string lrCorner = "╝";
            string vertical = "║";
            string horizontal = "═";

            string[] lines = s.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            

            int longest = 0;
            foreach(string line in lines)
            {
                if (line.Length > longest)
                    longest = line.Length;
            }
            int width = longest + 2; // 1 space on each side

            
            string h = string.Empty;
            for (int i = 0; i < width; i++)
                h += horizontal;

            // box top
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(ulCorner + h + urCorner);

            // box contents
            foreach (string line in lines)
            {
                double dblSpaces = (((double)width - (double)line.Length) / (double)2);
                int iSpaces = Convert.ToInt32(dblSpaces);

                if (dblSpaces > iSpaces) // not an even amount of chars
                {
                    iSpaces += 1; // round up to next whole number
                }

                string beginSpacing = "";
                string endSpacing = "";
                for (int i = 0; i < iSpaces; i++)
                {
                    beginSpacing += " ";

                    if (! (iSpaces > dblSpaces && i == iSpaces - 1)) // if there is an extra space somewhere, it should be in the beginning
                    {
                        endSpacing += " ";
                    }
                }
                // add the text line to the box
                sb.AppendLine(vertical + beginSpacing + line + endSpacing + vertical);
            }

            // box bottom
            sb.AppendLine(llCorner + h + lrCorner);

            // the finished box
            return sb.ToString();
        }

像这样的输出 输入图像描述

4

想要显示类似这样的内容吗?

这对我有用:

Console.OutputEncoding = Encoding.GetEncoding(866);
Console.WriteLine("┌─┐");
Console.WriteLine("│1│");
Console.WriteLine("└─┘");

[编辑]

回答评论中的子问题:

Console.OutputEncoding = Encoding.GetEncoding(866);
Console.WriteLine("  ┌─┐");
Console.WriteLine("  │1│");
Console.WriteLine("┌─┼─┘");
Console.WriteLine("│1│");
Console.WriteLine("└─┘");

@Alex,感谢你的示例。那肯定能解决问题。如果我错了,请纠正我,你所做的不是使用ASCII码,对吗?另外,“Encoding.GetEncoding(866)”是什么意思? - user712923
@Alex,你是如何绘制矩形的顶部的? - user712923
@user712923 - 按住Alt键,然后在数字键盘上输入218。这将显示┌。接着你需要用196和191做同样的操作。重要提示- 你需要使用数字键盘(NumLock已开启)。 - Alex Aza
@Alex,你非常非常有帮助。我可以问你最后一件事吗?抱歉。我已经画了一个矩形,我需要在右上角画另一个矩形,并在里面放置一个数字。有帮助的机会吗?谢谢。 - user712923

2

您可以使用CsConsoleFormat†在控制台中使用ASCII边框符号进行绘制。

使用“双”线在矩形内绘制数字:

ConsoleRenderer.RenderDocument(
    new Document()
        .AddChildren(
            new Border {
                    Stroke = LineThickness.Wide,
                    Align = HorizontalAlignment.Left
                }
                .AddChildren(1337)
        )
);

您可以更改 Stroke = LineThickness.Wide 行来更改线条的样式。 LineThickness.Single 会产生细单线,new LineThickness(LineWidth.Single, LineWidth.Wide) 会产生单竖线和双横线。

这是它的样子:

你也可以使用ConsoleBuffer类来显式地绘制行(参数名称已添加以增加清晰度):

using static System.ConsoleColor;

var buffer = new ConsoleBuffer(width: 6);
buffer.DrawHorizontalLine(x: 0, y: 0, width: 6, color: White);
buffer.DrawHorizontalLine(x: 0, y: 2, width: 6, color: White);
buffer.DrawVerticalLine(x: 0, y: 0, height: 3, color: White);
buffer.DrawVerticalLine(x: 5, y: 0, height: 3, color: White);
buffer.DrawString(x: 1, y: 1, color: White, text: "1337");
new ConsoleRenderTarget().Render(buffer);

† CsConsoleFormat 是由我开发的。


1
以上代码的问题在于有额外的空格,如果你画多个矩形,会造成混乱。 这里有一段递归绘制矩形的代码,没有额外的空格。
public class AsciDrawing
{
    public static void TestMain() {
        var w = Console.WindowWidth;
        var h = Console.WindowHeight;
        RecursiveDraw(16, 8, new Point(w/2-8, h/2-4), ConsoleColor.Black);
        Console.CursorTop = h;
        Console.CursorLeft = 0;
    }
    public static void RecursiveDraw(int Width, int Height, Point Location, ConsoleColor BorderColor) { 
        if(Width < 4 || Height < 2) return;
        Draw(Width, Height, Location, BorderColor); //Commnet this draw and and Uncomment Draw bellow to see the difference. 
        Thread.Sleep(500);
        //Comment or Uncomment to see how many recursive calls you want to make
        //The best is to comment all execpt 1 and then uncomment 1 by 1
        RecursiveDraw(Width/2, Height/2, new Point(Location.X-Width/4, Location.Y-Height/4), ConsoleColor.Green); //Left Top
        RecursiveDraw(Width / 2, Height / 2, new Point(Location.X + 3* Width / 4, Location.Y + 3* Height / 4), ConsoleColor.Red); //Right Bottom
        RecursiveDraw(Width / 2, Height / 2, new Point(Location.X + 3* Width / 4, Location.Y - Height / 4), ConsoleColor.Blue); //Right Top
        RecursiveDraw(Width / 2, Height / 2, new Point(Location.X - Width / 4, Location.Y + 3* Height / 4), ConsoleColor.DarkMagenta); // Left Bottom
        
        //Draw(Width, Height, Location, BorderColor);

    }
    public static void Draw(int Width, int Height, Point Location, ConsoleColor BorderColor)
    {
        Console.ForegroundColor = BorderColor;

        string s = "╔";
        string temp = "";
        for (int i = 0; i < Width; i++)
            s += "═";

        s += "╗" + "\n";
        
        Console.CursorTop = Location.Y;
        Console.CursorLeft = Location.X;
        Console.Write(s);



        for (int i = 0; i < Height; i++) {
            Console.CursorTop = Location.Y + 1 + i;
            Console.CursorLeft = Location.X;
            Console.WriteLine("║");
            Console.CursorTop = Location.Y + 1 + i;
            Console.CursorLeft = Location.X + Width+1;
            Console.WriteLine("║");
        }
           

        s = temp + "╚";
        for (int i = 0; i < Width; i++)
            s += "═";

        s += "╝" + "\n";

        
        Console.CursorTop = Location.Y+Height;
        Console.CursorLeft = Location.X;
        Console.Write(s);
        Console.ResetColor();
    }
}

public record Point(int X, int Y);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接