根据网上搜到的绘制树的例子,自己实践了一下部分纹理透明的方法,修改了其中颜色赋值时的红和蓝的顺序。具体代码如下
1.第一步:crate2.bmp须为24位真彩色位图 256*256
int LoadGLTextures() // Load Bitmaps And Convert To Textures
{
int Status=FALSE; // Status Indicator
AUX_RGBImageRec *TextureImage[1]; // Create Storage Space For The Texture
unsigned char *image;
memset(TextureImage,0,sizeof(void *)*1); // Set The Pointer To NULL ,若定义的为单指针TextureImage,则该句去掉,否则读取错误
if(TextureImage[0]=LoadBMP("Data/crate2.bmp") )
{
Status=TRUE;
int width,height;
width =TextureImage[0]->sizeX;
height=TextureImage[0]->sizeY;
FILE *fp;
fp=fopen("Data/crate2.bmp","rb");
if(!fp) return Status;
fseek(fp,54,SEEK_SET);////读取24位真彩色位图
image=(unsigned char *)malloc(width*height*3);
int rc;
rc=fread(image,sizeof(unsigned char),width*height*3,fp);
fclose(fp);
BYTE texture[256][256][4];//注意:每个像素占用4个字节,不是原来的3个。
for(int i=0;i<width;i++)
{
for(int j=0;j<height;j++)
{
//把颜色值写入 //树的例子 2 和0 相反,结果导致颜色不正确
texture[i][j][2] = (GLubyte)*(image+i*width*3+j*3);
texture[i][j][1] = (GLubyte)*(image+i*width*3+j*3+1);
texture[i][j][0] = (GLubyte)*(image+i*width*3+j*3+2);
//设置alpha值,假设白色为透明色
if(texture[i][j][0]==255 && texture[i][j][1]==255 && texture[i][j][2]==255)
texture[i][j][3] = 0;//透明,设为 0
else
texture[i][j][3] = 255;//不透明,设为 255, 也就是以后用的1.0
}
}
//映射纹理
glPixelStorei(GL_UNPACK_ALIGNMENT,1);
glTexImage2D(GL_TEXTURE_2D,0,4,width,height,0, GL_RGBA, GL_UNSIGNED_BYTE,texture);
gluBuild2DMipmaps(GL_TEXTURE_2D,4,width,height,GL_RGBA,GL_UNSIGNED_BYTE,texture);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
}
if (TextureImage[0]) // If Texture Exists
{
if (TextureImage[0]->data) // If Texture Image Exists
{
free(TextureImage[0]->data); // Free The Texture Image Memory
}
free(TextureImage[0]); // Free The Image Structure
}
return Status; // Return The Status
}
2.第二步:int DrawGLScene(GLvoid) 中 glBegin(GL_QUADS);前加上代码:
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER,0.9);//0.5可以换成任何在0~1之间的数