سؤال

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

}
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

Red Cross Indicates that an Exception has been thrown, you are not seeing it because it's being handled. Configure Visual Studio to break on exception throw to catch it.

An exception has been thrown. At first look your code:

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

will generate an IndexOutOfRangeException because verteces has 10 items but it will cycle from 0 to 10 (included so it'll search for 11 elements). It depends on what you want to do but you have to change the cycle to (removing the = from <=):

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

or to increment the size of verteces to 11.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top