c#画圆程序

之前,在网上找到过一个“画钻石”程序(一个错误的画圆程序),结果经过修改后得到了一个完整的实心圆。缺点是:速度较慢。

程序如下:

protected override void OnPaint(PaintEventArgs e)
      {
      Graphics myGraphics= e.Graphics;
      Pen myPen= new Pen( ForeColor,2 ); //定义画笔
      float radius= (float) ( Width/2.2 );        //半径
      const int partitionNum= 360;               //角度变化360次
      float angleUnit= (float) ( 2*Math.PI/partitionNum );//角度转为弧度
      int[] circleX= new int[partitionNum];  //横坐标数组
      int[] circleY= new int[partitionNum];  //纵坐标数组
      // center of the circle.
      int originX=ClientSize.Width/2;          //圆心横坐标
      int originY=ClientSize.Height/2;         //圆心纵坐标
      //store coordinates of the nodes on the circle verge.
      for ( int i=0;i<partitionNum;i++ )        //对横、纵坐标赋值
      {
      circleX[i] = (int) ( radius*Math.Cos( i*angleUnit ) ) + originX;
      circleY[i] = (int) ( radius*Math.Sin( i*angleUnit ) ) + originY;
      }

for (int i = 0; i < partitionNum ; i++)                //在每个横坐标处,让纵坐标“从该处纵坐标~360度时的纵坐标”变化
       {
           for (int j = i; j < partitionNum; j++)
            myGraphics.DrawLine(myPen, circleX[i], circleY[i], circleX[j], circleY[j]);
       }                                                             
//我对该循环的思路很不解,而且次循环要360*(360!)次,导致效率低下

因此,我把红色部分作了如下修改:

for (int i = 0,k=0,j=0; i < partitionNum; i++,j=i)  //此实心圆由360根竖线构成,每次X不变,Y从0~此处的纵坐标
       {
           myGraphics.DrawLine(myPen, circleX[i], circleY[k], circleX[i], circleY[j]);
       }                                                                  
//由于仅有360次循环,运行速度大大加快,且几乎没有瑕疵

之后,我想试试“从圆心以半径长度转一圈”的办法画圆:

for (int i = 0; i < partitionNum; i++)
       {
           myGraphics.DrawLine(myPen, originX, originY, circleX[i], circleY[i]);
       }                                                                
//此方法有一定的条状瑕疵,因为所有坐标为整型量(不精确)。随着半径增加,漏洞变大。

然后,我又想试试画圆圈,而不是实心的圆,程序如下:

for ( int i=0;i<partitionNum-1;i++ )
      {
           myGraphics.DrawLine( myPen,circleX[i],circleY[i],circleX[i+1],circleY[i+1] );
      }                                                           
//从该处(i处)的横纵坐标画到下一处(i+1处)的横纵坐标

这三次修改中,除了“用半径长度转一圈”的办法有瑕疵,不完美外,其他还是很让我满意的。

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s