简体   繁体   中英

How to draw transparent textures in LWJGL?

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;
}

you just need to add this:

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

in your init function :)

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 ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM