計算機圖形學(二)輸出圖元_20_章節總結_程式展示_折線圖和直方圖
阿新 • • 發佈:2019-02-12
折線圖和直方圖
第一個程式展示使用一條折線、一組多點標記和點陣圖字元標號來生成一年內按月的折線圖。儘管等寬字型與圖中的位置比較容易對齊,但此處給出了比例空間的字型。由於點陣圖左下角提供了當前光柵位置的參考,所以我們必須移動參考位置以使文字串中心與繪製資料的位置對齊。圖3.67給出了折線圖程式的輸出。
#include <GL/glut.h> GLsizei winWidth = 600, winHeight = 500; //Initial display window size. GLint xRaster = 25, yRaster = 150; // Initialize raster position. GLubyte label [36] = { 'J', 'a', 'n', 'F', 'e', 'b', 'M', 'a', 'r', 'A', 'p', 'r', 'M', 'a', 'y', 'J', 'u', 'n', 'J', 'u', 'l', 'A', 'u', 'g', 'S', 'e', 'p', 'O', 'c', 't', 'N', 'o', 'v', 'D', 'e', 'c'}; GLint dataValues [12] = {420, 342, 324, 310, 262, 185, 190, 196, 217, 240, 312, 438}; void init (void) { glClearColor (1.0, 1.0, 1.0, 1.0); //White display window. glMatrixMode (GL_PROJECTION); gluOrtho2D (0.0, 600.0, 0.0, 500.0); } void lineGraph (void) { GLint month, k; GLint x = 30; // Initialize x position for chart. glClear (GL_COLOR_BUFFER_BIT); // Clear display window. glColor3f (0.0, 0.0, 1.0); // Set line color to blue. glBegin (GL_LINE_STRIP); // Plot data as a polyline. for (k = 0; k < 12; k++) glVertex2i (x + k * 50, dataValues [k]); glEnd (); glColor3f (1.0, 0.0, 0.0); // Set marker color to red. for (k = 0; k < 12; k++){ // Plot data as asterisk polymarkers. glRasterPos2i (xRaster + k * 50, dataValues [k] - 4); glutBitmapCharacter (GLUT_BITMAP_9_BY_15, '*'); } glColor3f (0.0, 0.0, 0.0); // Set test color to black. xRaster = 20; // Display chart labels. for (month = 0; month < 12; month++) { glRasterPos2i (xRaster, yRaster); for (k = 3 * month; k < 3 * month + 3; k++) glutBitmapCharacter (GLUT_BITMAP_HELVETICA_12, label [k]); xRaster += 50; } glFlush ( ); } void winReshpeFcn (GLint newWidth, GLint newHeight) { glMatrixMode (GL_PROJECTION); glLoadIdetity ( ); gluOrtho2D (0.0, GLdouble (newWidth), 0.0, GLdouble (newHeight)); glClear (GL_COLOR_BUFFER_BIT); } void main (int argc, char** argv) { glutInit (&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowPosition (100, 100); glutInitWindowSize (winWidth, winHeight); glutCreateWindow ("Line Chart Data Plot"); init ( ); glutDisplayFunc (lineGraph); glutReshapeFunc (winReshpeFcn); glutMainLoop ( ); }
第二個程式使用同樣的資料集生成圖3.68所示的直方圖。該程式展示了矩形填充區及點陣圖字元標號的應用。
void barChart (void) { GLint month, k; glClear (GL_COLOR_BUFFER_BIT); // Clear display window. glColor3f (1.0, 0.0, 0.0); // Set bar color to red. for (k = 0, k < 12; k++) glRecti (20 + k * 50, 165, 40 + k * 50, dataValues [k]); glColor3f (0.0, 0.0, 0.0); // Set text color to black. xRaster = 20; // Display chart labels. for (month = 0; month < 12; month++){ glRasterPos2i (xRaster, yRaster); for (k = 3 * month; k < 3 * month + 3; k++) glutBitmapCharacter (GLUT_BITMAP_HELVETICA_12, label [h]); xRaster += 50; } glFlush ( ); }