﻿ VC++实现的OpenGL线性渐变色绘制操作示例 - 鸿网互联

# VC++实现的OpenGL线性渐变色绘制操作示例

```#include <GL/glut.h>
#include <iostream>
#include <cmath>
using namespace std;
const GLsizei width=640;
const GLsizei height=480;//设置窗口的宽和高
void myInit()
{
glClearColor(0,0,0,0);
}
void show()
{
GLsizei dw;
int n,i;
dw=2;
n=(width-1)/dw;
cout<<"n="<<n<<endl;
glClear(GL_COLOR_BUFFER_BIT);
GLsizei r,g,b;
for (i=0;i<n;i++)
{
//绘制应力云图的关键就是下面的这五种不同的颜色对应关系
//根据自己需要可以设置不同的等级，四种也是可以的
if (i>=0&&i<=n/5)
{
r=255;
g=i*255/(n/5);
b=0;
}
else if (i>n/5&&i<=2*n/5)
{
r=255-(i-n/5)*255/(n/5);
g=255;
b=0;
}
else if(i>2*n/5&&i<=3*n/5)
{
r=0;
g=255;
b=(i-2*n/5)*255/(n/5);
}
else if(i>3*n/5&&i<=4*n/5)
{
r=0;
g=255-(i-3*n/5)*255/(n/5);
b=255;
}
else
{
r=(i-4*n/5)*255/(n/5);
g=0;
b=255;
}
glColor3f(r/255.0f,g/255.0f,b/255.0f);
glRectf(1.0*i*dw,0.0,1.0*(i+1)*dw,height);
}
glFlush();
}
void reshape(int w,int h)
{
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glOrtho(0,w,0,h,-100,100);//设置视野的范围，(左,右,上,下,前,后)
glMatrixMode(GL_MODELVIEW);
}
int main(int argc,char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutInitWindowPosition(100,100);
glutInitWindowSize(width,height);
glutCreateWindow("应力云图绘制");
myInit();
glutDisplayFunc(show);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}

```

<