2014-07-23 47 views
0

我需要帮助在WinForm上画一条线。C#线条绘画问题

的代码我现在有大部分被拉断的MSDN:

using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

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

    private void Form1_Load(object sender, EventArgs e) 
    { 
     this.Invalidate(); 
    } 
    private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) 
    { 

     // Insert code to paint the form here. 
     Pen pen = new Pen(Color.FromArgb(255, 0, 0, 0)); 
     e.Graphics.DrawLine(pen, 10, 10, 300, 200); 
    } 
} 

}

目前,这个代码不画任何东西。

+3

This Works。你真的有一个事件处理程序将表单的Paint事件连接到你的方法吗? – vcsjones

+0

并且由于@PaulG不存在,请务必在完成后丢弃该笔 – Justin

+1

尝试重写OnPaint方法而不是调用Form1_Paint事件。你显然没有把事件联系起来。 – LarsTech

回答

1

您发布的代码没问题。它呈现在表格中间的黑线:

enter image description here

我怀疑你的问题是你没有表单的Paint事件订阅您Form1_Paint方法。你不能只是把这个方法放在那里,并期望它被神奇地称呼。

您可以修复,通过将它添加到您的窗体的构造函数:

public Form1() 
{ 
    InitializeComponent(); 
    this.Paint += Form1_Paint; 
} 

或者,也可以在设计,它做了同样的事件订阅做到这一点,它只是塔克斯它拿走的InitializeComponent()内。

+0

是的,就是这样。我还想问另外一个问题:我应该使用Windows窗体来绘制一个包含几个几何形状的简单二维游戏的图形吗?还是有另一种更有效的方法,我应该使用? – palmerito0

+0

@ palmerito0我不是游戏的专家,所以我不能说真的。然而,依赖于GDI的WinForms并不是硬件加速的,所以如果你每秒重绘30次,你会看到高CPU使用率。我会看看使用DirectX的游戏框架。 – vcsjones

+0

等待,但不是DirectX for C++? – palmerito0

0

根据MSDN:

using System.Drawing;

Pen myPen; 
myPen = new Pen(System.Drawing.Color.Red); 
Graphics formGraphics = this.CreateGraphics(); 
formGraphics.DrawLine(myPen, 0, 0, 200, 200); 
myPen.Dispose(); 
formGraphics.Dispose(); 

你的代码实际上看起来不错,你确定方法射击?

+1

或更好的地方创建笔对象,使用()语句 – Justin