java - LWJGL png纹理透明度(textureColour.a白色而不是黑色)

标签 java opengl transparency lwjgl alpha

我有由 PNG 图片纹理化的草模型。我得到白色背景颜色而不是黑色,这是我想要的。为什么会这样?我应该做什么来解决这个问题?我正在使用 LWJGL 3PNGDecoder.jar

纹理加载器代码:

public int loadTexture(String fileName) {
    ByteBuffer buf = null;
    int tWidth = 0;
    int tHeight = 0;

    try {
        // Open the PNG file as an InputStream
        InputStream in = new FileInputStream("res/" + fileName + ".png");
        // Link the PNG decoder to this stream
        PNGDecoder decoder = new PNGDecoder(in);

        // Get the width and height of the texture
        tWidth = decoder.getWidth();
        tHeight = decoder.getHeight();

        // Decode the PNG file in a ByteBuffer
        buf = ByteBuffer.allocateDirect(
                4 * decoder.getWidth() * decoder.getHeight());
        decoder.decode(buf, decoder.getWidth() * 4, Format.RGBA);
        buf.flip();

        in.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    // Create a new texture object in memory and bind it
    int textureId = GL11.glGenTextures();
    GL13.glActiveTexture(textureId);
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId);

    // All RGB bytes are aligned to each other and each component is 1 byte
    GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);

    // Upload the texture data and generate mip maps (for scaling)
    GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB, tWidth, tHeight, 0,
            GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf);
    GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);

    // Setup the ST coordinate system
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);

    // Setup what to do when the texture has to be scaled
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER,
            GL11.GL_NEAREST);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER,
            GL11.GL_LINEAR_MIPMAP_LINEAR);

    return textureId;
}

最佳答案

如果你想让透明纹理看起来透明,你必须先启用混合。将以下内容放入您的 OpenGL 初始化代码中。

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
<小时/>

您还在内部以 RGB 而不是 RGBA 格式存储纹理。

GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB, tWidth, tHeight, 0,
    GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf);

应该变成

GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, tWidth, tHeight, 0,
    GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf);

关于java - LWJGL png纹理透明度(textureColour.a白色而不是黑色),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32992575/

相关文章:

OpenGL 深度测试未按预期工作

c++ - 如何在 C++ 中创建一个独立的可执行程序?

java - 在 Scala 注释中使用常量的最佳实践

java - 如何反编译.jar 文件?

java - 如何测试使用数据库登录的Servlet?

css - 背景透明度影响文本

java - 我正在使用 .getRGB() 和 .setRGB() 来获取 BufferedImage 的一部分,如何复制透明度?

java - 在循环内发出值 (RxJava)

java - 我可以为 GLES20.glDrawElements 函数提供多少个索引?

css - IE6透明+单选按钮无法点击