how to take input from text to draw shapes on screen c#

不打扰是莪最后的温柔 提交于 2019-12-11 14:14:20

问题


Hi all I am trying to create a program that takes commands from the user to draw shapes on the screen. The program should have basic commands to draw shapes and a clear command to clear the screen afterwards, the user should be able to type moveTo in the text box and the pen should move the the coordinates they set it to then the user should be able to type in the shape they want to draw(circle(radius), rectangle(width, height), triangle(side, side, side). I have got it to work for the rectangle as i want however struggling to implement the other parts can anyone help.

public partial class Form1 : Form
{
    String input;
    Bitmap drawOutput;

    String command, command2, command3;
    int x, y;

    public Form1()
    {
        InitializeComponent();

        drawOutput = new Bitmap(OutputBox.Size.Width, OutputBox.Size.Height);
        OutputBox.Image = drawOutput;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Graphics g;
        g = Graphics.FromImage(drawOutput);

        Pen mypen = new Pen(Color.Black);
        g.Clear(Color.White);
        g.Dispose();
    }

    private void CMDBox_TextChanged(object sender, EventArgs e)
    {
        input = CMDBox.Text;
    }

    private void ExecuteBtn_Click(object sender, EventArgs e)
    {
        string[] spilt = input.Split(' ');
        foreach (String words in spilt)
        {
            command = spilt[0];
            command2 = spilt[1];
            command3 = spilt[2];

            x = Int32.Parse(command2);
            y = Int32.Parse(command3);

            Graphics g;
            g = Graphics.FromImage(drawOutput);
            Pen pen = new Pen(Color.Black, 5);

            if (command == "circle")
            {
                g.DrawEllipse(pen, 0, 0, x, y);

                setImage(g);

            }
            else if (command == "rectangle")
            {
                g.DrawRectangle(pen, 0, 0, x, y);

                setImage(g);


            }
        }

    }

    public void setImage(Graphics g)
    {
        g = Graphics.FromImage(drawOutput);

        OutputBox.Image = drawOutput;

        g.Dispose();
    }
}

The basic context of this program is to create a really basic programming language which takes the users input and display it on screen


回答1:


You don't need to declare a class level bitmap (drawOutput) nor create Graphics object from it. You need to do the drawing in the Paint event handler. Try the following:

  • Declare enumeration for your shapes, class level variables to hold the type of the shape, x and y coordinates, and the size of the shape w and h.
enum Shapes
{
    Ellipse,
    Rectangle,
    Line
}

int x, y, w, h;
Shapes shape;
  • Validate the user's input in the ExecuteBtn click event, assign the values, and call the OutputBox.Invalidate() if the input is correct.
var cmd = textBox1.Text.Split(' ');
var validCmds = Enum.GetNames(typeof(Shapes));

if (cmd.Length < 5 || !validCmds.Contains(cmd[0], StringComparer.OrdinalIgnoreCase))
{
    MessageBox.Show("Enter a valid command.");
    return;
}

if(!int.TryParse(cmd[1], out x) || 
    !int.TryParse(cmd[2], out y) ||
    !int.TryParse(cmd[3], out w) ||
    !int.TryParse(cmd[4], out h))                    
{
    MessageBox.Show("Enter a valid shape");
    return;
}
shape = (Shapes)validCmds.ToList().FindIndex(a => a.Equals(cmd[0], StringComparison.OrdinalIgnoreCase));
OutputBox.Invalidate();
  • Draw the shape in the Paint event.
private void OutputBox_Paint(object sender, PaintEventArgs e)
{
    if (w > 0 && h > 0)
    {
        e.Graphics.Clear(Color.White);
        e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        using (Pen pn = new Pen(Color.Black, 5))
        {
            switch (shape)
            {
                case Shapes.Ellipse:
                    e.Graphics.DrawEllipse(pn, x, y, w, h);
                    break;
                case Shapes.Rectangle:
                    e.Graphics.DrawRectangle(pn, x, y, w, h);
                    break;
                case Shapes.Line:
                    e.Graphics.DrawLine(pn, x, y, w, h);
                    break;
            }
        }
    }
}

Better yet, TerribleDog's approach as he commented.

  • Create the Shape class to enumerate your shapes, declare properties for them, and a method to parse a given command string and outs the required shape on success:
public class Shape
{
    #region enums.

    public enum Shapes
    {
        Ellipse,
        Rectangle,
        Line
    }
    #endregion

    #region Constructors

    public Shape()
    { }

    public Shape(Shapes shape, int x, int y, int width, int height)
    {
        ThisShape = shape;
        X = x;
        Y = y;
        Width = width;
        Height = height;
    }

    #endregion

    #region Properties

    public Shapes ThisShape { get; set; } = Shapes.Ellipse;
    public int X { get; set; }
    public int Y { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }

    #endregion

    #region Methods

    public static bool TryParse(string input, out Shape result)
    {
        result = null;

        if (string.IsNullOrEmpty(input))
            return false;

        var cmd = input.Split(' ');
        var validCmds = Enum.GetNames(typeof(Shapes));

        if (cmd.Length < 5 || !validCmds.Contains(cmd[0], StringComparer.OrdinalIgnoreCase))
            return false;

        int x, y, w, h;

        if (!int.TryParse(cmd[1], out x) ||
            !int.TryParse(cmd[2], out y) ||
            !int.TryParse(cmd[3], out w) ||
            !int.TryParse(cmd[4], out h))
            return false;

        if (w <= 0 || h <= 0)
            return false;

        var shape = (Shapes)validCmds.ToList().FindIndex(a => a.Equals(cmd[0], StringComparison.OrdinalIgnoreCase));

        result = new Shape(shape, x, y, w, h);
        return true;
    }

    #endregion

}
  • In your Form, declare a shape variable:
Shape shape;
  • The ExecuteBtn click event:
shape = null;

if (!Shape.TryParse(textBox1.Text, out shape))
{
    MessageBox.Show("Enter a valid command.");
    return;
}
OutputBox.Invalidate();
  • Finally, your paint event:
private void OutputBox_Paint(object sender, PaintEventArgs e)
{
    if (shape != null)
    {
        e.Graphics.Clear(Color.White);
        e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        using (Pen pn = new Pen(Color.Black, 5))
        {
            switch (shape.ThisShape)
            {
                case Shape.Shapes.Ellipse:
                    e.Graphics.DrawEllipse(pn, shape.X, shape.Y, shape.Width, shape.Height);
                    break;
                case Shape.Shapes.Rectangle:
                    e.Graphics.DrawRectangle(pn, shape.X, shape.Y, shape.Width, shape.Height);
                    break;
                case Shape.Shapes.Line:
                    //Note: the Width and Height properties play here the X2 and Y2 roles.
                    e.Graphics.DrawLine(pn, shape.X, shape.Y, shape.Width, shape.Height);
                    break;
            }
        }
    }
}

Good luck.



来源:https://stackoverflow.com/questions/58580456/how-to-take-input-from-text-to-draw-shapes-on-screen-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!