How to draw transparent textures in LWJGL?

徘徊边缘 提交于 2019-12-13 03:31:06

问题


I have been trying to draw a transparent texture in LWJGL. However, the code I have doesn't seem to work. Whenever I run the code, the transparent image appears but the background is completely black.

Here's what I mean by completely black, but the image is fine:

I have been able to draw non-transparent textures, but so far I've had no luck with drawing this one correctly.

I would like to know what is missing/incorrect in this code.

Code for drawing texture:

//draw transparent texture    
GL11.glMatrixMode(GL11.GL_TEXTURE);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glPushMatrix();    

GL11.glColor4d(1,1,1,1);

texture.bind();

GL11.glTranslated(0.5,0.5,0.0);
GL11.glRotated(270-this.getAngle(),0.0,0.0,1.0);
GL11.glTranslated(-0.5,-0.5,0.0);

GL11.glBegin(GL11.GL_QUADS);
{
    GL11.glTexCoord2f(0,0);
    GL11.glVertex2d(this.getX(), this.getY());
    GL11.glTexCoord2f(1,0);
    GL11.glVertex2d(this.getX(),(this.getY()+this.getHeight()));
    GL11.glTexCoord2f(1,1);
    GL11.glVertex2d((this.getX()+this.getWidth()),(this.getY()+this.getHeight()));
    GL11.glTexCoord2f(0,1);
    GL11.glVertex2d((this.getX()+this.getWidth()), this.getY());
}
GL11.glEnd();

GL11.glPopMatrix();
GL11.glDisable(GL11.GL_BLEND);
GL11.glMatrixMode(GL11.GL_MODELVIEW);

Here's the code that loads the texture from the file:

private Texture loadTexture(String key){
    try {
        //in this case, key refers to a valid power of 2, transparent png
        return TextureLoader.getTexture("PNG", new FileInputStream(new File("res/"+key+".png")));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        return null;
}

回答1:


The above code does not seem to have a problem. By using the simple code from the Slick-Util Library - Part 1 - Loading Images for LWJGL and replacing the render() method with your code I was able to correctly see transparency using this RGBA image of an up arrow:

Please make sure that you are clearing your colorbuffer in a color other than black i.e. use

GL11.glClearColor(0.7f, 0.7f, 0.7f, 1.0f);  // try with red (1, 0, 0, 1) green (0, 1, 0, 1) to check the image's transparent area.

If this doesn't work for your case, please post a full runnable example because the problem must lie in the rest of your code.




回答2:


you just need to add this:

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

in your init function :)



来源:https://stackoverflow.com/questions/18280517/how-to-draw-transparent-textures-in-lwjgl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!