Search code examples
c#graphicsmultidimensional-arraydrawrectangle

Why is DrawRectangle drawing a cross inside my PictureBox


I'm trying to draw 10 rectangles, but when I use g.DrawRectangle() it is drawing a cross as shown below:

Drawing cross

I'm creating Vertex objects that contain a getRectangle() function which returns a Rectangle object for that vertex.

I was hoping to create these objects and show them as Rectangles on the pictureBox.

Here's my code

    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());
        }
    }

Code for Vertex class

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);

    }
}

Code for Graph class

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);
        }
    }

}

Solution

  • Looks like an exception in your draw loop

    last call to:

    newGraph.verteces[0,i]
    

    fails with OutOfRangeException you shoul iterate not to i <= 10, but to i < 10