首页 > 解决方案 > C#上的图形试图在画布上画一条线

问题描述

无法在 Visual Studio 上画一条线。它输出控制台命令,但不绘制任何内容。不太清楚发生了什么..我错过了什么吗?我已经按照我的讲师制定的所有教程进行操作,但只是没有。

下面分别是画布代码和表单代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace AssignmentProper
{
    public class Canvass
    {
        Graphics g;
        Pen Pen;
        int xPos, yPos;

        public Canvass(Graphics g)
        {
            this.g = g;
            xPos = yPos = 0;
            Pen = new Pen(Color.Red, 2);
        }


        public void DrawLine(int toX, int toY)
        {
            g.DrawLine(Pen, xPos, yPos, toX, toY);
            xPos = toX;
            yPos = toY;
        }

        public void DrawSquare(int width)
        {
            g.DrawRectangle(Pen, xPos, yPos, xPos + width, yPos + width);
        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AssignmentProper
{
    public partial class Form1 : Form
    {
        Bitmap OutputBitmap = new Bitmap(640, 480);
        Canvass MyCanvass;

        public Form1()
        {
            InitializeComponent();
            MyCanvass = new Canvass(Graphics.FromImage(OutputBitmap));
        }

        private void Button1_Click(object sender, EventArgs e)
        {
    
        }

        private void TextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void commandLine_KeyDown(object sender, KeyEventArgs e)
        {
            Console.WriteLine("key down");
            if(e.KeyCode == Keys.Enter)
            {
                String Command = commandLine.Text.Trim().ToLower();

                if(Command.Equals("line") == true)
                {
                    MyCanvass.DrawLine(160, 120);
                    Console.WriteLine("LINE");
                }
                else if (Command.Equals("square") == true)
                {
                    MyCanvass.DrawSquare(25);
                    Console.WriteLine("SQUARE");
                }
                commandLine.Text = "";
                Refresh();
            }
        }

        private void PictureBox1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.DrawImageUnscaled(OutputBitmap, 0, 0);
        }

    }
}

不知道发生了什么,只是根本没有画任何东西。任何建议将不胜感激。

标签: c#graphics

解决方案


推荐阅读