日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

C語言實(shí)現(xiàn)繪制貝塞爾曲線的函數(shù)_C 語言

作者:編程小魚六六六 ? 更新時間: 2023-01-13 編程語言

程序截圖

簡單說明

這個函數(shù)就是

void drawBezierCurve(COLORREF color, const unsigned int len, ...)

color 是貝塞爾曲線的顏色,len 是畫出貝塞爾曲線所需要的點(diǎn)的個數(shù),最少 1 個,不要亂傳。之后的參數(shù)傳的就是畫出貝塞爾曲線要的點(diǎn),數(shù)據(jù)類型為 Vec2。

這個函數(shù)實(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 為直線上任意一個點(diǎn)的橫縱坐標(biāo)值,t 為未知參數(shù)。

對于一條線段,可以根據(jù)線段上兩個端點(diǎn)轉(zhuǎn)化為參數(shù)方程:

x = x0 + (x1 - x0) * t

y = y0 + (y1 - y0) * t

t ∈ [0, 1]

將這條線段分為 CURVEPIECE 份,t 從 0 到 1 一份一份地加,就能得到這條線段上均勻分布的 CURVEPIECE 個點(diǎn)。

貝塞爾曲線就是對 n 個點(diǎn)連線組成的 n 條(線段上對應(yīng)份的點(diǎn))的連線的 (n - 1) 條(線段的對應(yīng)份點(diǎn))的連線的……直到最后 1 條線段上(對應(yīng)份點(diǎn)的連線)。

這個曲線的算法如果用遞歸的話可能會占用很大內(nèi)存,畢竟每一輪的點(diǎn)的值都保存下來了,我這里用循環(huán)做,空間占用只有兩輪內(nèi)點(diǎn)的值。

代碼實(shí)現(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;
}

原文鏈接:https://blog.csdn.net/yx5666/article/details/128315874

欄目分類
最近更新