【问题标题】:Draw line in c#在c#中画线
【发布时间】:2013-04-07 01:07:23
【问题描述】:

我是 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);

【问题讨论】:

  • 那你面临的问题是什么?
  • 表格上没有出现该行。
  • 好的。你把上面的代码放在哪个函数里了?
  • 运行它会发生什么?
  • 我把它放在 InitializeComponent() 调用之后

标签: c# winforms graphics drawing


【解决方案1】:

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);
        }

【讨论】:

  • 这有效,但为什么我提供的代码在 msdn 网站上不起作用。
  • @JohnB:如果您将代码放在 Paint 事件处理程序中,您的代码将绘制一些东西。
  • 不要使用 CreateGraphics。使用已经可用的Graphics对象:g = e.Graphics
  • 你应该(使用 Pen myPen = new Pen){ } 或至少确保 .dispose() 它。
  • @JohnB:您的代码画出一些东西。但是,如果你把它放在构造函数中,它会在第一次创建表单时画线,但在显示表单之前。当表格显示出来时,它会再次被重绘,因为你的代码不会被执行来绘制线条,所以它们不会出现。每次重新绘制表单时都需要绘制线条(它们不会被“记住”),而正确的位置是在 OnPaint() 中。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您应该在要在其上绘制线条的对象的 Paint 事件中进行绘制。因此,只需使用 Paint 事件的 EventArgs 参数中的 e 变量中的 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
    

    【讨论】:

      【解决方案4】:
       private void Form1_Paint(object sender, PaintEventArgs e)
          {
              ....
          }
      

      并从您的初始化程序运行它:

       public Form1()
          {
              InitializeComponent();
      
              this.Paint += new System.Windows.Forms.PaintEventHandler(Form1_Paint);
          }
      

      【讨论】:

        猜你喜欢
        • 2011-06-25
        • 2022-11-03
        • 1970-01-01
        • 2011-01-17
        • 2021-01-02
        • 1970-01-01
        • 2010-10-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多