C# 在面板上画线不显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13943387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:10:44  来源:igfitidea点击:

draw line on panel not showing up

c#winformsgraphics

提问by Badmiral

I have a Panelcalled panel1and I am trying to draw a line on my panel1using this code:

我有一个Panel电话panel1,我正在尝试panel1使用以下代码在我的上画一条线:

var g = panel1.CreateGraphics();
var p = new Pen(Color.Black, 3);

var point1 = new Point(234,118);
var point2 = new Point(293,228);

g.DrawLine(p, point1, point2);

But nothing is showing up. Any ideas? This is in a windows form.

但什么都没有出现。有任何想法吗?这是一个窗口形式。

采纳答案by keyboardP

Handle the Panel's Paint eventand put it in there. What's happening is that it's being drawn once in the constructor but then being drawn over in the Paintevent everytime it's called.

处理 Panel 的Paint 事件并将其放在那里。发生的事情是它在构造函数中被绘制一次,但Paint每次被调用时都会在事件中被绘制。

private void panel1_Paint(object sender, PaintEventArgs e)
{
    base.OnPaint(e);
    using(Graphics g = e.Graphics)
    {
       var p = new Pen(Color.Black, 3);
       var point1 = new Point(234,118);
       var point2 = new Point(293,228);
       g.DrawLine(p, point1, point2);
    }
}

回答by Mike Webb

Put it in some event after the form has been created and shown on the screen and it should work fine.

在创建表单并在屏幕上显示后将其放入某个事件中,它应该可以正常工作。

It's best to put it in the Paint event, as keyboardP stated, but it will not show up if called before the form is shown on the screen.

最好将它放在 Paint 事件中,如 keyboardP 所述,但如果在窗体显示在屏幕上之前调用它,它将不会显示。

To test this you can add a button and add the code to the click event:

要对此进行测试,您可以添加一个按钮并将代码添加到单击事件中:

private void button1_Click(object sender, EventArgs e)
{
    using (Graphics g = panel1.CreateGraphics())
    {
        g.DrawLine(new Pen(Color.Back, 3), new Point(234,118), new Point(293,228));
    }
}

回答by Combine

To see your drawing - you can simply make a button with a Click Event and draw when the button is clicked. For example:

要查看您的绘图 - 您可以简单地创建一个带有 Click 事件的按钮,并在单击该按钮时进行绘制。例如:

private void btnDraw_Click(object sender, EventArgs e)
{
    Graphics dc = drawingArea.CreateGraphics();
    Pen BlackPen = new Pen(Color.Black, 2);
    dc.DrawLine(BlackPen, 0, 0, 200, 200);

    BlackPen.Dispose();
    dc.Dispose();
}    

Oh, and by the way "drawingArea" is the (Name) of either a PictureBox or Panel you have added to your form (to draw in it).

哦,顺便说一句,“drawingArea”是您添加到表单中的图片框或面板的(名称)(用于在其中绘制)。

回答by Nick

If you follow the other answers and still your drawings are not showing up try removing all controls from the control that is being drawn to. The other controls may be covering whatever you are trying to draw.

如果您按照其他答案操作,但仍然没有显示您的绘图,请尝试从正在绘制的控件中删除所有控件。其他控件可能涵盖您尝试绘制的任何内容。