1. 程式人生 > >計算機圖形學常用演算法實現2 中點畫圓法

計算機圖形學常用演算法實現2 中點畫圓法

在winform下實現,如果在其他環境,思路完全一樣,只需替換畫圖的函式即可。
中點畫圓法算是中點畫線法思路的一種實際應用,本質是一樣的。
1.對稱畫圖,只需要畫1/8部分的圓(我們的函式裡面取45~90度部分),其他部分對稱畫過去即可,對稱畫圖的程式碼如下:

        void drawCirclePoints(Point p1,Point p2)
        {
            Graphics g = this.CreateGraphics();
            Brush pe = new SolidBrush(Color.Red);
            g.FillRectangle(pe, new RectangleF(p2.X,p2.Y, 1, 1));
            g.FillRectangle(pe, new RectangleF(2*p1.X-p2.X, p2.Y, 1, 1));
            g.FillRectangle(pe, new RectangleF(p2.X, 2*p1.Y-p2.Y, 1, 1));
            g.FillRectangle(pe, new RectangleF(2*p1.X-p2.X,2*p1.Y-p2.Y, 1, 1));
            g.FillRectangle(pe, new RectangleF(p1.X + p2.Y - p1.Y, p1.Y + p2.X - p1.X, 1, 1));
            g.FillRectangle(pe, new RectangleF(p1.X - p2.Y + p1.Y, p1.Y + p2.X - p1.X, 1, 1));
            g.FillRectangle(pe, new RectangleF(p1.X - p2.Y + p1.Y, p1.Y - p2.X + p1.X, 1, 1));
            g.FillRectangle(pe, new RectangleF(p1.X + p2.Y - p1.Y, p1.Y - p2.X + p1.X, 1, 1));
        }

2.中點畫圓
由於r的值不一定是整數,因此可能不好和中點畫線法一樣乘某個數取整,採用浮點數進行計算。
當然,如果採用Point 和 r這樣的引數進行寫函式,可以進行下一步的優化。

        void MidPointCircle(Point p1, Point p2)
        {
            float r = (float)Math.Sqrt((p1.X-p2.X)* (p1.X - p2.X)+ (p1.Y - p2.Y) * (p1.Y - p2.Y));
            float x = p1.X;
            float y = p1.Y + r;
            float d = 1.25f - r ;
            while (x-p1.X <= y-p1.Y)
            {
                if (d < 0)
                    d += 2 * x + 3 - 2 * p1.X;
                else
                {
                    d += 2 * (x - y) + 5 + 2 * p1.Y - 2 * p1.X;
                    y--;
                }
                x++;
                drawCirclePoints(p1,new Point ((int)(x+0.5),(int)(y+0.5)));
            }
            
        }

效果如下所示:
在這裡插入圖片描述