直線繪製演算法原始碼

來源:互聯網
上載者:User

以前在學校裡學過圖形學,但效果很不好。而現在感覺就很不夠用了。

決定重新重新來過,不斷督促自己學習並實踐這方面的內容。

首先從最基礎的直線繪製演算法開始。

演算法一原始碼

// 直線的DDA(數值微分)演算法// 直線起始點(xa, ya)// 直線終止點(xa, ya)void lineDDA(int xa, int ya, int xb, int yb, HDC hDC, COLORREF crColor){int dx = xb - xa, dy = yb - ya;int steps; int loop;float xIncrement, yIncrement;float x = (float)xa, y = (float)ya;if (abs(dx) > abs(dy)) steps = abs(dx);else steps = abs(dy);xIncrement = dx / (float)steps; yIncrement = dy / (float)steps; SetPixel(hDC, xa, ya, crColor);// 初始點x += 0.5;// 因四捨五入而添加的y += 0.5;// 先行相加就儲存在浮點值x、y裡了for (loop = 0; loop < steps; loop++){x += xIncrement;y += yIncrement;SetPixel(hDC, (int)x, (int)y, crColor);}}

 

演算法二原始碼:

// 直線的Bresenham演算法// 直線起始點(xa, ya)// 直線終止點(xa, ya)void lineBresenham(int xa, int ya, int xb, int yb, HDC hDC, COLORREF crColor){int dx = abs(xb - xa), dy = abs(yb - ya);// 這兩個值只與絕對值有關int x = xa, y = ya;int xIncrement, yIncrement, loop;// 步進量/累加變數bool interchange;int p;if (xb - xa > 0)xIncrement = 1;else if (xb - xa == 0)xIncrement = 0;else xIncrement = -1;if (yb - ya > 0)yIncrement = 1;else if (yb - ya == 0)yIncrement = 0;else yIncrement = -1;SetPixel(hDC, x, y, crColor);// 繪製初始點// 處理特殊情況的直線繪製if (dy == 0){// 水平線for (loop = 0; loop < dx; loop++){x += xIncrement;SetPixel(hDC, x, y, crColor);}}else if (dx == 0){// 豎直線for (loop = 0; loop < dy; loop++){y += yIncrement;SetPixel(hDC, x, y, crColor);}}else if (dx == dy){// 或各個象限的角平分線for (loop = 0; loop < dx; loop++){x += xIncrement;y += yIncrement;SetPixel(hDC, x, y, crColor);}}else {// 處理一般情形下的直線繪製// 若斜率絕對值小於1,不需交換if (dx > dy)interchange = false;// 若斜率絕對值大於1,交換dx和dy執行計算,後續步進累加時需要做相應變更else {int temp = dx;dx = dy;dy = temp;interchange = true;}p = - dx;for (loop = 0; loop < dx; loop++){// 首先處理步進變數if (interchange)y += yIncrement;// 若交換了x和y則每次迴圈步進y值else x += xIncrement;// 若沒有交換,則每次迴圈步進x值p += 2 * dy;// 因為每次迴圈都需要加上2dy,初始值時需要相加再這裡加上if (p >= 0){// 此時需要步進另一個量if (interchange)x += xIncrement;else y += yIncrement;p -= 2 * dx;}SetPixel(hDC, x, y, crColor);// 畫點}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.