使用面向对象方法封装OpenGL函数(三)

今天实现的是在Window对象上绘制矩形,并且可以定制矩形的坐标、长宽、边框的大小的颜色、是否填充、以及填充时的颜色。 主要的思想就是先用线条绘制出边框,,然后在里面绘制出矩形,再根据设定的是否填充的模式,选择此矩形的透明度,若显示,则透明度为1,;不显示,则透明度为0

下面是Rectangle类的代码:

/**************************************************文件名:Rectangle.h功能:绘制矩形***************************************************/#ifndef _RECTANGLE_H_#define _RECTANGLE_H_#include “Object.h”#include “Color.h”#include “OpenGL\glut.h”class Rectangle : public Object {public:Rectangle(){init();//默认设置}Rectangle(int x, int y, int width, int height) {init();setRectangle(x, y, width, height);}//设置矩形的四边void setRectangle(int x, int y, int width, int height) {this->x = x;this->y = y;this->width = width;this->height = height;}//设置边框void setBorder(int w,Color c) {this->borderWidth = w;this->borderColor = c;}//绘图函数void show(){int increment = borderWidth / 2;glColor3d(borderColor.R, borderColor.G, borderColor.B); //设置边框颜色glLineWidth(borderWidth);//设置边框宽度glBegin(GL_LINES);//开始绘制矩形glVertex2i(x-increment, y);glVertex2i(x + width+increment, y);glVertex2i(x + width, y);glVertex2i(x + width, y + height);glVertex2i(x + width +increment, y + height);glVertex2i(x-increment, y + height);glVertex2i(x, y + height);glVertex2i(x, y);glEnd();glEnable(GL_BLEND);//设置可以混合色glBlendFunc(GL_SRC_ALPHA, GL_ONE);//指定像素算法glColor4f(fillColor.R, fillColor.G, fillColor.B,//指定矩形颜色以及透明度(mode==FILLING?1.0:0.0));glRectf(x + borderWidth/2, y + borderWidth/2,//绘制矩形x + width – borderWidth/2, y + height – borderWidth/2);}public:int x, y, width, height;//矩形的坐标以及长宽Color borderColor, fillColor; mode;//绘图模式private://初始化函数void init(){x = y = 0;width = height = 100;borderColor = Color(0, 0, 0); //边框颜色默认为白色fillColor = Color(255, 255, 255); //填充颜色默认为白色borderWidth = 1;//边框宽度默认为1mode = NOTFILLING;}public://矩形的填充模式FILLING = NOTFILLING = 1; //不填充矩形};#endif

下面是一段测试代码:

main(int argc ,char* argv[]) {int w = 400, h = 300;Window window(string(“Hello”), 100, 100, w, h);window.create();Rectangle rect;rect.x = 10;//设置坐标xrect.y = 10;//设置坐标yrect.width = 200;//设置宽度rect.height = 200;//设置高度rect.borderWidth = 5;//设定边框宽度rect.mode = rect.FILLING;//设置可填充rect.borderColor = Color(255, 0, 0); //设置填充颜色window.add(&rect);//给window对象添加矩形组件Application* app = new Application();app->init(argc, argv);app->add(window);app->show();delete app;return 0;}//*/

效果图如下: 宽度为5的红色边框矩形里面填充了白色区域

生命不是一场赛跑,而是一次旅行。比赛在乎终点,而旅行在乎沿途风景。

使用面向对象方法封装OpenGL函数(三)

相关文章:

你感兴趣的文章:

标签云: