在c#中画线

时间:2011-03-11 20:47:20

标签: c# winforms graphics drawing

我是c#的新手,我正在努力在表格中划一条线。这是我到目前为止的代码。

Graphics g;

g = this.CreateGraphics();

Pen myPen = new Pen(Color.Red);
myPen.Width = 30;
g.DrawLine(myPen, 30, 30, 45, 65);

g.DrawLine(myPen, 1, 1, 45, 65);

4 个答案:

答案 0 :(得分:20)

OnPaint

中试用
protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g;

            g = e.Graphics;

            Pen myPen = new Pen(Color.Red);
            myPen.Width = 30;
            g.DrawLine(myPen, 30, 30, 45, 65);

            g.DrawLine(myPen, 1, 1, 45, 65);
        }

答案 1 :(得分:5)

这不是一个真正的问题,因为你没有说出你所看到的。

执行此操作的正确方法是使用表单的Paint事件处理程序。从e参数中获取图形对象。试试看,让我们知道你看到了什么。

答案 2 :(得分:3)

您应该绘制要绘制线条的对象的Paint事件。因此,只需使用Paint事件的e参数中的EventArgs变量中的Graphics对象。这是一个VB.NET示例:

Private Sub ExampleLinkLabel_Paint(ByVal sender As Object, _
                                   ByVal e As System.Windows.Forms.PaintEventArgs) _
                                   Handles lnkMyLinkLabel.Paint

    Dim lbl As LinkLabel = DirectCast(sender, Label)
    Dim pen1 As New System.Drawing.Pen(Color.Black, 1)
    Dim topLeft As New Point(0, 0)
    Dim topRight As New Point(lbl.Width - 1, 0)
    Dim bottomLeft As New Point(0, lbl.Height - 1)
    Dim bottomRight As New Point(lbl.Width - 1, lbl.Height - 1)

    e.Graphics.DrawLine(pen1, topLeft, topRight)
    e.Graphics.DrawLine(pen1, bottomLeft, bottomRight)
    e.Graphics.DrawLine(pen1, topRight, bottomRight)

End Sub

答案 3 :(得分:3)

 private void Form1_Paint(object sender, PaintEventArgs e)
    {
        ....
    }

并从初始化程序运行它:

 public Form1()
    {
        InitializeComponent();

        this.Paint += new System.Windows.Forms.PaintEventHandler(Form1_Paint);
    }