2012-03-15 59 views
2

我想画10米的矩形,但是当我使用g.DrawRectangle()它画十字,如下图所示:为什么DrawRectangle的画过我的图片框里面

Drawing cross

我创建顶点对象它包含一个getRectangle()函数,该函数返回该顶点的一个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); 
     } 
    } 

} 
+0

我所知道的是,无论是在您的代码还是在他们的代码中都会发生一些异常。尝试删除一些逻辑,直到你画出一些东西,以便调试问题 – 2012-03-15 09:58:59

+1

正如其他人所说的,“交叉”是抛出异常的结果。如果你没有吞下堆栈中较高的异常,那么你的代码中可能会有一个错误,很容易找到并修复。毕竟,这里有一个重要的教训。 – 2012-03-15 10:01:39

回答

2

外貌就像你平局循环异常

最后呼吁:

newGraph.verteces[0,i] 

失败OutOfRangeException 你建议立即进行删除不重复,以i <= 10,但i < 10

+0

即使我删除'for'循环,并放上'g.DrawRectangle(pen1,newGraph.verteces [0,1] .getRectangle());'它仍然显示十字:( – Luke 2012-03-15 09:58:35

+0

,如果我把'g .DrawRectangle(pen1,new Rectangle(10,10,10,10));' – Luke 2012-03-15 09:59:15

+0

修复了两个循环,一个在Graph构造函数中,一个在paintPictureBox方法中 – 2012-03-15 10:02:22

1

异常被抛出。首先看你的代码:

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

将产生一个IndexOutOfRangeException因为verteces有10个项目,但它会循环从0到10(含所以它会搜索11元)。这取决于你想做的事,但你必须改变周期(去除=<=):

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

或到verteces规模增加至11

+0

+1谢谢你的帮助:) :) – Luke 2012-03-15 10:05:58

相关问题