Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么这画不出任何东西?_C#_Winforms_System.drawing - Fatal编程技术网

C# 为什么这画不出任何东西?

C# 为什么这画不出任何东西?,c#,winforms,system.drawing,C#,Winforms,System.drawing,我的代码中有以下if语句: //global variables int x1; int y1; int x2; int y2; int counter = 0; private void pictureBox1_Click(object sender, EventArgs e) { if (radioButtonDrawLine.Checked) { if (counter == 0) { x1 = Cursor.Pos

我的代码中有以下if语句:

//global variables
int x1;
int y1;
int x2;
int y2;
int counter = 0;

private void pictureBox1_Click(object sender, EventArgs e)
{
    if (radioButtonDrawLine.Checked)
    {
        if (counter == 0)
        {
            x1 = Cursor.Position.X;
            y1 = Cursor.Position.Y;
            counter++;                        
        }    
        else
        {
            x2 = Cursor.Position.X;
            y2 = Cursor.Position.Y;

            if (counter == 1)
            {
                Graphics g = CreateGraphics();
                g.DrawLine(Pens.Black, x2, y2, x1, y1);
            }
            counter = 0;
        }
    }
}
我应该在我的picturebox上点击两次,每次点击都会保存x和y。第二次单击时,应在两个坐标之间绘制一条线。
但这不起作用,我也不明白为什么。有人能告诉我怎么了吗?

你应该在绘画活动中画画。类似于以下的方法应该可以工作:

//global variables
private Point? p1;
private Point? p2;
private int counter = 0;

private void pictureBox1_Click(object sender, EventArgs e)
{
    if (radioButtonDrawLine.Checked)
    {
        if (counter == 0)
        {
            p1 = pictureBox1.PointToClient(new Point(Cursor.Position.X, Cursor.Position.Y));
            counter++;
        }
        else
        {
            p2 = pictureBox1.PointToClient(new Point(Cursor.Position.X, Cursor.Position.Y));
            pictureBox1.Refresh();
            counter = 0;
        }
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (p1.HasValue && p2.HasValue)
    {
        e.Graphics.DrawLine(Pens.Black, p1.Value.X, p1.Value.Y, p2.Value.X, p2.Value.Y);
    }
}

Refresh调用是在创建第二个点后强制重新绘制。请注意,我还使用了Point结构而不是Int来存储坐标,因为这样可以将坐标保存在逻辑组中,并使其更清楚地显示出来。

您的代码存在两个主要问题

首先,在窗体上调用CreateGraphics,而不是图片框-因此,如果您确实在正确的位置绘制,则图片框将隐藏该图形

第二,您的坐标是关闭的,因为Cursor.Position返回屏幕坐标,而不是相对于要绘制的控件的坐标。但这已经是不必要的了——首先不应该使用Click事件,而应该使用MouseUp。单击是一种不同的操作,完全不需要使用定点设备,例如按下按钮上的空格。要处理鼠标单击,请使用鼠标事件。作为奖励,您将在事件处理程序的参数中获得单击的本地坐标:


最后,如果希望图像持久化,我建议不要直接绘制到picture box图形对象,而是创建一个内存中的位图来保存图形,并让picture box根据需要重新绘制。否则,导致重新绘制图片框的任何内容也将清除到目前为止所绘制的任何内容。

radioButtonDrawLine.Checked==true?仍然不起作用。我认为在不使用==True的情况下应该是一样的。如果这样做,那么在捕获坐标后立即执行PointToClient,而不是在Paint事件中。控件可能同时移动,这也会使行移动。