標籤:opengl 物件導向 演算法 .電腦圖形學
今天封裝了一個Line類,負責在昨天寫的視窗上繪製線條。
OpenGL繪圖是通過給glBegin函數設定參數達成的,繪製線條有三個不同的參數:
GL_LINES : 繪製串連兩個點的線段(繪製的端點位於glBegin函數與glEnd函數之間)
GL_LINE_STRIP : 繪製首尾相連的折線
GL_LINE_LOOP : 繪製首尾相連的折線,並在最後將起始點與終點相串連,閉合路徑
下面是Line類的代碼:
/***********************************************檔案名稱:Line.h功能:畫布,在上面可以畫點,畫線條和橢圓、矩形************************************************/#ifndef _LINE_H_#define _LINE_H_#include "Point.h"#include "Window.h"class Line : public Object {public:Line(){this->mode = this->LINE_MODE_DEFAULT;this->status = this->LINE_INIT;}//起始點,每次設定起始點,都需同時記錄此時是起始點狀態,若此時已是起始點//則刪除上一個起始點void moveTo(Point& p){if(this->status == this->LINE_START) {points.pop_back();return;}points.push_back(p);this->status = this->LINE_START;}//畫線終止點,若一開始是終止點,不允添加void LineTo(Point& p){if (this->status == this->LINE_START) {this->points.push_back(p);this->status = this->LINE_END;return;}}//添加節點數組void addPoints(Point* p,int size) {for (int i = 0; i < size; i++){this->points.push_back(p[i]);}}//設定線條顏色void setColor(Color& color){this->color = color;}//設定畫線模式void setMode(int mode){switch (mode){case LINE_MODE_DEFAULT:mode = GL_LINES; break;case LINE_MODE_LOOP:mode = GL_LINE_LOOP; break;case LINE_MODE_NOTLOOP:mode = GL_LINE_STRIP; break;}this->mode = mode;}public:static const int LINE_MODE_LOOP = 0;//設定線條首尾相接static const int LINE_MODE_NOTLOOP = 1;//不設定線條首尾相接static const int LINE_MODE_DEFAULT = 2;//預設繪製線段private://畫線狀態static const int LINE_INIT = 0;//初始狀態static const int LINE_START = 1;//起始點狀態static const int LINE_END = 2;//終止點狀態private:int mode;//畫線模式,預設為不串連vector<Point> points;//點集合int status;//畫線狀態Color color;//指定顏色public:void show(){//將被Window調用繪圖虛函數glColor3f(color.R, color.G, color.B);glBegin(mode);for (int i = 0; i < points.size(); i++) {glVertex2i(points[i].X, points[i].Y);}glEnd();}};#endif
下面畫了一個五角星的執行個體:
(裡面的Window和Application、Point類在部落格(一))
#include "Window.h"#include "Application.h"#include "Line.h"//隱藏控制台視窗#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")int main(int argc ,char* argv[]) {int w = 400, h = 300;Window window(string("Hello"), 100, 100, w, h);window.create();Line line;//畫五角星line.setMode(line.LINE_MODE_LOOP);Point p[5] = {Point(10, 200),Point(200, 200),Point(30, 20),Point(105, 240),Point(180, 20),};line.setColor(Color(255, 0, 0));line.addPoints(p, 5);window.add(&line);Application* app = new Application();app->init(argc, argv);app->add(window);app->show();delete app;return 0;}//*/
:
這裡直接使用了OpenGL的畫線函數,用於繪製直線的電腦圖形學演算法有DDA演算法和Bresenham演算法等。
【OpenGL基礎篇】——使用物件導向方法封裝OpenGL函數(二)