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

字號(hào):


    通過上一節(jié)的例子我們已經(jīng)知道一些簡(jiǎn)單的使用顏色的方法。這一節(jié)我們進(jìn)一步講講顏色的使用。
    例2:本例子使用顏色引索模式繪制8個(gè)不同顏色的球體,如圖二所示。閱讀此例時(shí),請(qǐng)主要關(guān)注函數(shù)palette和DrawColotFans。
    glIndex設(shè)置當(dāng)前顏色索引。參數(shù)為當(dāng)前顏色索引。本例中g(shù)lIndexd 函數(shù)的參數(shù)j+1對(duì)應(yīng)palette中auxSetOneColor函數(shù)中的i+1,auxSetOneColor函數(shù)的后三個(gè)函數(shù)制定對(duì)應(yīng)的顏色,顏色值由變量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]);//設(shè)置顏色
    }
    }
    void DrawColorFans(void)
    {
    GLint j;
    glTranslatef(-15,-15,0);
    for(j = 0;j<8;j++)
    {
    glIndexd(j+1);//設(shè)置當(dāng)前顏色索引
    /*在不同位置繪制球體*/
    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個(gè)不同顏色的球體