今天封装了一个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; } //*/
效果图: