我目前正在使用java& lwjgl并在我的主菜单中尝试绘制背景图像。出于某种原因,无论使用何种纹理加载和绘图技术,图像都会被完全搞砸。
这就是:
这就是它应该是这样的:
这是我加载纹理的代码:
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();
}
任何想法?
答案 0 :(得分: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));