C語言實現(xiàn)繪制貝塞爾曲線的函數(shù)
程序截圖

簡單說明
這個函數(shù)就是
void drawBezierCurve(COLORREF color, const unsigned int len, ...)
color 是貝塞爾曲線的顏色,len 是畫出貝塞爾曲線所需要的點的個數(shù),最少 1 個,不要亂傳。之后的參數(shù)傳的就是畫出貝塞爾曲線要的點,數(shù)據(jù)類型為 Vec2。
這個函數(shù)實現(xiàn)的基礎(chǔ)是參數(shù)方程,用參數(shù)方程將一條直線轉(zhuǎn)化為一個參數(shù)的方程,如:
A * x + B * y + C=0 可以轉(zhuǎn)化為 x = x0 - B * t;y = y0 + A * t,x0、y0 為直線上任意一個點的橫縱坐標值,t 為未知參數(shù)。
對于一條線段,可以根據(jù)線段上兩個端點轉(zhuǎn)化為參數(shù)方程:
x = x0 + (x1 - x0) * t
y = y0 + (y1 - y0) * t
t ∈ [0, 1]
將這條線段分為 CURVEPIECE 份,t 從 0 到 1 一份一份地加,就能得到這條線段上均勻分布的 CURVEPIECE 個點。
貝塞爾曲線就是對 n 個點連線組成的 n 條(線段上對應(yīng)份的點)的連線的 (n - 1) 條(線段的對應(yīng)份點)的連線的……直到最后 1 條線段上(對應(yīng)份點的連線)。
這個曲線的算法如果用遞歸的話可能會占用很大內(nèi)存,畢竟每一輪的點的值都保存下來了,我這里用循環(huán)做,空間占用只有兩輪內(nèi)點的值。
代碼實現(xiàn)
// 程序:畫貝塞爾曲線的函數(shù)
// 編譯環(huán)境:Visual Studio 2019,EasyX_20211109
//
#include <graphics.h>
#include <conio.h>
using namespace std;
// 畫貝塞爾曲線的函數(shù),包括這個 Vec2 結(jié)構(gòu)體
struct Vec2
{
double x, y;
};
void drawBezierCurve(COLORREF color, const unsigned int len, ...)
{
if (len <= 0) return;
va_list list;
va_start(list, len);
Vec2* temp = new Vec2[len];
for (int i = 0; i < len; i++)
temp[i] = va_arg(list, Vec2);
va_end(list);
if (len == 1)
{
putpixel(temp->x, temp->y, color);
return;
}
Vec2* parent = nullptr, * child = nullptr;
Vec2 lastPoint = temp[0];
setlinecolor(color);
for (double LineNum = 0; LineNum < 1 + 1.0 / 100; LineNum += 1.0 / 100)
{
int size = len;
parent = temp;
while (size > 1)
{
child = new Vec2[size - 1];
for (int i = 0; i < size - 1; i++)
{
child[i].x = parent[i].x + (parent[i + 1].x - parent[i].x) * LineNum;
child[i].y = parent[i].y + (parent[i + 1].y - parent[i].y) * LineNum;
}
if (parent != temp)delete[] parent;
parent = child;
size--;
}
line(lastPoint.x, lastPoint.y, parent->x, parent->y);
lastPoint.x = parent->x;
lastPoint.y = parent->y;
delete[] parent;
parent = nullptr;
child = nullptr;
}
delete[] temp;
}
int main()
{
initgraph(640, 480);
Vec2 a = { 100, 80 };
Vec2 b = { 540, 80 };
Vec2 c = { 540, 400 };
Vec2 d = { 100, 400 };
setlinecolor(BLUE);
line(a.x, a.y, b.x, b.y);
line(b.x, b.y, c.x, c.y);
line(c.x, c.y, d.x, d.y);
drawBezierCurve(RED, 4, a, b, c, d);
_getch();
closegraph();
return 0;
}到此這篇關(guān)于C語言實現(xiàn)繪制貝塞爾曲線的函數(shù)的文章就介紹到這了,更多相關(guān)C語言繪制貝塞爾曲線內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言中的自定義類型之結(jié)構(gòu)體與枚舉和聯(lián)合詳解
今天我們來學習一下自定義類型,自定義類型包括結(jié)構(gòu)體、枚舉、聯(lián)合體,小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考2022-06-06
C++實現(xiàn)神經(jīng)BP神經(jīng)網(wǎng)絡(luò)
這篇文章主要為大家詳細介紹了C++實現(xiàn)神經(jīng)BP神經(jīng)網(wǎng)絡(luò),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-05-05

