2017-04-10 210 views
1

我目前正在使用java & lwjgl在我的主菜单中尝试绘制背景图像。出于某种原因,无论我使用何种纹理加载和绘图技术,图像都会被完全搞砸。LWJGL螺纹纹理

这是发生了什么:

而这正是它应该是这样的:

Link

这是我的加载纹理代码:

private int loadTexture(String imgName) { 
    try { 
     BufferedImage img = ImageIO.read(JarStreamLoader.load(imgName)); 
     ByteBuffer buffer = BufferUtils.createByteBuffer(img.getWidth() * img.getHeight() * 3); 
     for (int x = 0; x < img.getWidth(); x++) { 
      for (int y = 0; y < img.getHeight(); y++) { 
       Color color = new Color(img.getRGB(x, y)); 
       buffer.put((byte) color.getRed()); 
       buffer.put((byte) color.getGreen()); 
       buffer.put((byte) color.getBlue()); 
      } 
     } 
     buffer.flip(); 
     int textureId = glGenTextures(); 
     glBindTexture(GL_TEXTURE_2D, textureId); 
     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.getWidth(), img.getHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, buffer); 
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 
     return textureId; 
    } catch (Exception e) { 
     throw new RuntimeException(e); 
    } 
} 

这就是我的渲染代码:

public static void drawRect(int x, int y, int width, int height, Color color) { 
    glColor4f(color.getRed()/255, color.getGreen()/255, color.getBlue()/255, 1.0F); 
    glBegin(GL_QUADS); 

    glTexCoord2f(0.0f, 0.0f); 
    glVertex2d(x, y); 

    glTexCoord2f(0.0f, 1.0F); 
    glVertex2d(x, y + height); 

    glTexCoord2f(1.0F, 1.0F); 
    glVertex2d(x + width, y + height); 

    glTexCoord2f(1.0F, 0.0f); 
    glVertex2d(x + width, y); 

    glEnd(); 
} 

任何想法?

回答

1

您正在以错误的顺序添加像素。你需要做的是在这个顺序:

for (int y = 0; y < img.getHeight(); y++) 
    for (int x = 0; x < img.getWidth(); x++) 

需要注意的是OpenGL的原点在左下角,所以你可能需要翻转在y轴上的图像,以及:

Color color = new Color(img.getRGB(x, img.getHeight() - y - 1)); 
+0

谢谢,它现在工作完美:) – Twometer