ImageBox图形错误

时间:2012-05-23 23:53:16

标签: c# visual-studio-2010 graphics

我正在尝试将多边形列表绘制到图像框中。到目前为止,我只是在屏幕的左上角有一条黑色斜线。要点如下:

20,20 0,20 20,0 40,40

200100 0,20 20,0 20,20

100,200 0,200 200,0 250,450

150130 1,20 20,0 10,20

    private void pictureBox1_Paint_1(object sender, PaintEventArgs e)
    {
        int jobIndex = 0;
        int trussIndex = 0;

        Graphics g = e.Graphics;
        foreach (Member m in jobArray[jobIndex].trusses[trussIndex].members)
        {
            Point[] pointArray = new Point[m.poly.Points.Count()];
            //m.poly.Points.CopyTo(pointArray, 0);
            int index =0;
            foreach(System.Windows.Point p in m.poly.Points)
            {
                pointArray[index].X = (int)p.X;
                pointArray[index].Y = (int)p.Y;
                index++;
            }
            Pen myPen = new Pen(Color.Black);
            SolidBrush myBrush = new SolidBrush(m.color);

            g.DrawPolygon(myPen, pointArray);
            g.FillPolygon(myBrush, pointArray);

        }
    }

关于为什么多边形没有出现在图像框上的任何想法? 颜色不是问题,也不是盒子的大小

1 个答案:

答案 0 :(得分:0)

看起来您使用Paint事件来调用此方法,确保在调用时可以获得数据。不会经常调用paint事件,因此如果添加要绘制的数据,则需要调用pictureBox1.Invalidate()方法来强制绘制事件。

我相信你迟早会看到这个,但你应该创建一个图像(Bitmap)对象并将其分配给PictureBox的Image属性。然后使用Graphics.FromImage(_image)获取图形对象。如果你不这样做,那么如果窗口被覆盖,你的图像将不会停留,然后重新聚焦,或者你将它拖出屏幕,然后再回到那里。

private Bitmap _bitMap;
private Graphics _graphic;
Pen myPen;

public Constructor()
{
    _bitMap = new Bitmap(pictureBox1.Width,pictureBox1.Height);
    _graphic = Graphics.FromImage(_bitMap);
    pictureBox1.Image = _bitMap;
    myPen = new Pen(Color.Black);
}
private void DataAdded()
{
    int jobIndex = 0;
    int trussIndex = 0;

    foreach (Member m in jobArray[jobIndex].trusses[trussIndex].members)
    {
        //Pen myPen = new Pen(Color.Black); //Don't instantiate in a loop
        SolidBrush myBrush = new SolidBrush(m.color);
        _graphic.DrawPolygon(myPen, m.poly.Points.ToArray());
        _graphic.FillPolygon(myBrush, m.poly.Points.ToArray());
    }
    pictureBox1.Image = _bitMap; //Don't think you need this, but I don't remember
}

希望这有帮助