C# Forms - Using Paint methods?

Deadly 提交于 2020-01-05 12:58:20

问题


In c# forms I have created a new paint method:

private void thisPolygon(PaintEventArgs e)
{
    Pen clrBlue = new Pen(Color.Blue, 3);
    Point[] Wst = new Point[5];
    Wst[0] = new Point(20, 350);
    Wst[1] = new Point(110, 200);
    Wst[2] = new Point(200, 190);
    Wst[3] = new Point(210, 275);
    Wst[4] = new Point(190, 400);
    Wst[5] = new Point(50, 390);
    e.Graphics.DrawPolygon(clrBlue, Wst);
}

Now, how do I call it? I can't make it work, this doesn't work:

private void Form1_Load(object sender, EventArgs e)
{
    thisPolygon(); ///I've tried adding some stuff in brackets area, failed.
}

回答1:


You have a few different problems.

(1) Array Capacity. Your array is initialized with 5 storage locations, but you are attempting to set a sixth value.

Point[] Wst = new Point[5]; // 5 indexes
...
Wst[5] = new Point(50, 390); // Tries to access a sixth, but is out of bounds

Change this to.

Point[] Wst = new Point[6];

Remember that arrays are zero-based indexed.

(2) Not using OnPaint. You're calling thisPolygon in the OnLoad method, which won't persist your drawing. Move your call to the OnPaint method of the form.

protected override void OnPaint(PaintEventArgs e) {
    base.OnPaint(e);
    thisPolygon();
}

(3) Not passing PaintEventArgs. You're not passing in any event arguments to your thisPolygon method, and it won't even compile as it is. Pass in the paint arguments from the OnPaint method.

protected override void OnPaint(PaintEventArgs e) {
    base.OnPaint(e); // Pass in e
    thisPolygon();
}


来源:https://stackoverflow.com/questions/10581599/c-sharp-forms-using-paint-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!