Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#线绘制问题_C#_.net_Graphics_Line_Pen - Fatal编程技术网

C#线绘制问题

C#线绘制问题,c#,.net,graphics,line,pen,C#,.net,Graphics,Line,Pen,我需要帮助在WinForm上画一条线 我目前拥有的代码大部分来自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()

我需要帮助在WinForm上画一条线

我目前拥有的代码大部分来自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);
    }
}
}

目前,此代码根本不绘制任何内容。

根据MSDN:

使用系统图

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

您的代码实际上看起来很好,您确定该方法正在启动吗?

您的代码(如发布的)很好。它在窗体中间呈现黑色线条:

我怀疑您的问题是您没有订阅
Form1\u-Paint
方法的表单的
Paint
事件。你不能只是把这个方法放在那里,然后期待它被神奇地调用

您可以通过将其添加到窗体的构造函数来修复此问题:

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

或者,您可以在designer中执行此操作,它执行相同的事件订阅,它只需将其塞进
InitializeComponent()

中即可。您是否真的有一个事件处理程序将表单的绘制事件连接到您的方法?正如@PaulG所回避的,请确保在完成ITT时处理笔,尝试重写OnPaint方法,而不是调用Form1_绘制事件。您显然没有连接事件。除了vcslones提示(您需要注册事件,例如在“属性事件”页面中),您应该确保表单没有黑色背景色,否则您将看不到黑色线条。@Justin,继续创建一个钢笔对象并绘制一个形状会更有效吗?还是我应该反复使用同一个钢笔对象?或者更好的是,使用using()语句syup,就是这样。我还想问另一个问题:我是否应该使用windows窗体为一个包含一些几何形状的简单2d游戏绘制图形?还是我应该使用另一种更有效的方法?@palmerito0我并不是游戏专家,所以我真的不能说。然而,依赖GDI的WinForms并不是硬件加速的,所以如果每秒重新绘制30次,您将看到CPU使用率很高。我会研究一个使用DirectX。BooT的游戏框架,但不是C++的DirectX?@ PalMeIo0DirectX只是一个可以从多种语言调用的API。例如,WPF很好地利用了DirectX,DirectX周围有大量的托管包。