在Winforms中绘制一条线

Jos*_*orp 6 .net c# system.drawing winforms

我在以简单的窗体形式在组框中绘制线条时遇到问题.

这是我的代码:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();                        
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);            
            DrawLShapeLine(groupBox1.CreateGraphics(), 10, 10, 20, 40);
        }

        public void DrawLShapeLine(System.Drawing.Graphics g, int intMarginLeft, int intMarginTop, int intWidth, int intHeight)
        {
            Pen myPen = new Pen(Color.Black);
            myPen.Width = 2;
            // Create array of points that define lines to draw.
            int marginleft = intMarginLeft;
            int marginTop = intMarginTop;
            int width = intWidth;
            int height = intHeight;
            int arrowSize = 3;
            Point[] points =
             {
                new Point(marginleft, marginTop),
                new Point(marginleft, height + marginTop),
                new Point(marginleft + width, marginTop + height),
                // Arrow
                new Point(marginleft + width - arrowSize, marginTop + height - arrowSize),
                new Point(marginleft + width - arrowSize, marginTop + height + arrowSize),
                new Point(marginleft + width, marginTop + height)
             };

            g.DrawLines(myPen, points);
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果我将DrawLShapeLine方法附加到按钮单击事件,它绘制正常,但它不会在窗体的负载上绘制.

请指教.

Nat*_*ium 24

快而脏:

如何创建宽度为1像素的面板并给它一个backgroundcolor?

  • 如果你不*想要*对角线并且想要避免GDI +,那么很好的提示. (3认同)

Fre*_*örk 4

Paint为的事件连接一个事件处理程序,GroupBoxDrawLShapeLine从该事件处理程序内进行调用。然后,您应该使用Graphics事件参数中提供的对象:

private void groupBox1_Paint(object sender, PaintEventArgs e)
{
    DrawLShapeLine(e.Graphics, 10, 10, 20, 40);
}
Run Code Online (Sandbox Code Playgroud)

GroupBox正如您的代码现在看起来的那样,当表单需要绘画时,它将尝试进行绘画。组框可以在任何其他场合绘制,这将使您绘制的线条消失。