OpenGL編程輕松入門之使用顏色

字號:


    通過上一節(jié)的例子我們已經知道一些簡單的使用顏色的方法。這一節(jié)我們進一步講講顏色的使用。
    例2:本例子使用顏色引索模式繪制8個不同顏色的球體,如圖二所示。閱讀此例時,請主要關注函數palette和DrawColotFans。
    glIndex設置當前顏色索引。參數為當前顏色索引。本例中glIndexd 函數的參數j+1對應palette中auxSetOneColor函數中的i+1,auxSetOneColor函數的后三個函數制定對應的顏色,顏色值由變量rgb[8][3]定義。
    #include <GL/glut.h>
    #include <GL/glaux.h>
    void init(void)
    {
    glClearColor(1.0,1.0,1.0,1.0);
    glClear(GL_COLOR_BUFFER_BIT);
    glShadeModel(GL_SMOOTH);
    }
    void palette(void)
    {
    GLint i;
    static GLfloat rgb[8][3]={{1,0,0},{1,0,0.5},{1,0,1},
    {0,0,1},{0,1,1},{0,1,0},{1,1,0},{1,0.5,0}};
    for(i = 0;i<8;i++)
    {
    auxSetOneColor(i+1,rgb[i][0],rgb[i][1],rgb[i][2]);//設置顏色
    }
    }
    void DrawColorFans(void)
    {
    GLint j;
    glTranslatef(-15,-15,0);
    for(j = 0;j<8;j++)
    {
    glIndexd(j+1);//設置當前顏色索引
    /*在不同位置繪制球體*/
    glTranslatef(j,j-1,0);
    glutSolidSphere(1,20,20);
    }
    }
    void CALLBACK display(void)
    {
    palette();
    DrawColorFans();
    glFlush();
    }
    void CALLBACK reshape(GLsizei w,GLsizei h)
    {
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(100,1,1,20);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0,0,-15);
    }
    void main()
    {
    auxInitDisplayMode(AUX_SINGLE|AUX_INDEX);
    auxInitPosition(100,100,500,500);
    auxInitWindow("draw the color sphere");
    init();
    auxReshapeFunc(reshape);
    auxMainLoop(display);
    }
    
    圖二:8個不同顏色的球體