绘制矩形不起作用

DrawRectangle doesn't work

我在 class 上创建了一个矩形。函数 "DrawRectangle" 不绘制任何东西。我把代码放在下面:

我自己的 class (Unidad.cs):

class Unidad
{
    //Constructor
    public Unidad(string tipo, int movimiento)
    {
        tipoUnidad = tipo;
        movimientoUnidad = movimiento;
    }

    //Propiedades
    public string tipoUnidad {get; set;}
    public int movimientoUnidad { get; set; }

    //Método para dibujar unidad
    public void colocar(MouseEventArgs e)
    {            
        Form1 myf = new Form1();

        using (Graphics g = myf.picboxFondo.CreateGraphics())
        {
            Pen pen = new Pen(Color.Red, 2);

            g.DrawRectangle(pen, e.X, e.Y, 20, 20);

            pen.Dispose();
            g.Dispose();
        }
    }
}

主要class:

public partial class Form1 : Form
{
    //Prueba de clase
    Unidad prueba;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        picboxFondo.Size = ClientRectangle.Size;
        prueba = new Unidad("I", 20);
    }

    private void picboxFondo_MouseDown(object sender, MouseEventArgs e)
    {
        prueba.colocar(e);
    }
}

我有 picboxFondo 修改器 public。所有编译都正确并且工作完美,但是当我转到 g.DrawRectangle 时,我看到所有值都正常,但它没有绘制任何东西。

你能帮帮我吗?

谢谢!

您正在为您的 Form1 class 创建一个 新实例 并尝试利用该新实例的 PictureBox (这根本不显示)。

相反,您可以将要绘制的控件作为参数传递给 colocar 方法:

public void colocar(Point p, Control control)
{
    using (Graphics g = control.CreateGraphics())
    {
        using (Pen pen = new Pen(Color.Red, 2))
        {
            g.DrawRectangle(pen, p.X, p.Y, 20, 20);
        }
    }
}

并在您的表单中这样称呼它:

private void picboxFondo_MouseDown(object sender, MouseEventArgs e)
{
    prueba.colocar(e.Location, picboxFondo);
}

我也改变了方法,让你只传递MouseEventArgsLocation,因为你的绘图方法不需要知道任何关于鼠标事件的信息,只需要知道[=17] =].
请注意,无需在 PenGraphics 上调用 Disposeusing 语句会为您执行此操作。
您可以考虑使用 .NET naming conventions 并重命名您的方法 Colocar.