【OpenGL基礎篇】——使用物件導向方法封裝OpenGL函數(三)——繪製矩形,基礎篇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; //邊框顏色與填充顏色 int borderWidth; //邊框寬度 int mode; //繪圖模式private: //初始化函數 void init(){ x = y = 0; width = height = 100; borderColor = Color(0, 0, 0); //邊框顏色預設為白色 fillColor = Color(255, 255, 255); //填充顏色預設為白色 borderWidth = 1; //邊框寬度預設為1 mode = NOTFILLING; }public: //矩形的填充模式 static const int FILLING = 0; //填充矩形 static const int NOTFILLING = 1; //不填充矩形};#endif
下面是一段測試代碼:
#include "Window.h"#include "Application.h"#include "Line.h"#include "Rectangle.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(); Rectangle rect; rect.x = 10; //設定座標x rect.y = 10; //設定座標y rect.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的紅色邊框矩形裡面填充了白色地區