2

我正在尝试绘制 10 个矩形,但是当我使用g.DrawRectangle()它时,它正在绘制一个十字,如下所示:

画十字

我正在创建包含 getRectangle() 函数的 Vertex 对象,该函数返回Rectangle该顶点的对象。

我希望创建这些对象并将它们显示为pictureBox.

这是我的代码

    private System.Drawing.Graphics g;
    private System.Drawing.Pen pen1 = new System.Drawing.Pen(Color.Blue, 2F);

    public Form1()
    {
        InitializeComponent();

        pictureBox.Dock = DockStyle.Fill;
        pictureBox.BackColor = Color.White;
    }

    private void paintPictureBox(object sender, PaintEventArgs e)
    {
        // Draw the vertex on the screen
        g = e.Graphics;

        // Create new graph object
        Graph newGraph = new Graph();

        for (int i = 0; i <= 10; i++)
        {
           // Tried this code too, but it still shows the cross
           //g.DrawRectangle(pen1, Rectangle(10,10,10,10);

           g.DrawRectangle(pen1, newGraph.verteces[0,i].getRectangle());
        }
    }

顶点类的代码

class Vertex
{
    public int locationX;
    public int locationY;
    public int height = 10;
    public int width = 10;

    // Empty overload constructor
    public Vertex()
    {
    }

    // Constructor for Vertex
    public Vertex(int locX, int locY)
    {
        // Set the variables
        this.locationX = locX;
        this.locationY = locY;
    }

    public Rectangle getRectangle()
    {
        // Create a rectangle out of the vertex information
        return new Rectangle(locationX, locationY, width, height);

    }
}

Graph 类的代码

class Graph
{
    //verteces;
    public Vertex[,] verteces = new Vertex[10, 10];

    public Graph()
    {

        // Generate the graph, create the vertexs
        for (int i = 0; i <= 10; i++)
        {
            // Create 10 Vertexes with different coordinates
            verteces[0, i] = new Vertex(0, i);
        }
    }

}
4

3 回答 3

2

在您的绘图循环中看起来像一个例外

最后一次调用:

newGraph.verteces[0,i]

失败了OutOfRangeException 你应该迭代不是i <= 10,而是i < 10

于 2012-03-15T09:57:00.633 回答
2

Red Cross 表示已引发异常,您看不到它,因为它正在处理中。将 Visual Studio 配置为在异常抛出时中断以捕获它。

于 2012-03-15T09:58:27.997 回答
1

已抛出异常。乍一看你的代码:

for (int i = 0; i <= 10; i++)

将生成一个,IndexOutOfRangeException因为verteces有 10 个项目,但它会从 0 循环到 10(包括在内,因此它将搜索 11 个元素)。这取决于您想要做什么,但您必须将循环更改为(删除=from <=):

for (int i = 0; i < 10; i++)

或将大小verteces增加到 11。

于 2012-03-15T09:57:43.307 回答