我正在学习有关在屏幕上渲染文本的教程,但似乎找不到加载字体纹理的有效方法。我尝试了 slick 库,但它已经过时了:它使用 lwjgl2 的方法,在 lwjgl3 中不再存在,所以它抛出一个java.lang.NoSuchMethodError
. 在网上我发现glfw(集成在lwjgl中)有一个方法叫glfwLoadTexture2D
,不过貌似只有glfw的C++版本才有。我还在openGL utils中找到了一个名为 的方法gluBuild2DMipmaps
,但看起来lwjgl没有它:类GLUtil
和GLUtils
存在,但它们没有任何类似的方法,实际上它们几乎是空白的。
我正在寻找加载纹理并将纹理的 ID 返回给我以供进一步使用的东西,可能不使用外部库。
LWJGL3 没有像以前的 slick 那样准备好使用纹理加载功能。但是你可以很容易地使用 png 图像,你需要的只是 PNGLoader 你可以在这里找到它:https ://mvnrepository.com/artifact/org.l33tlabs.twl/pngdecoder/1.0
(Slicks PNG 解码器也基于它)
使用它的全功能方法
public static Texture loadTexture(String fileName){
//load png file
PNGDecoder decoder = new PNGDecoder(ClassName.class.getResourceAsStream(fileName));
//create a byte buffer big enough to store RGBA values
ByteBuffer buffer = ByteBuffer.allocateDirect(4 * decoder.getWidth() * decoder.getHeight());
//decode
decoder.decode(buffer, decoder.getWidth() * 4, PNGDecoder.Format.RGBA);
//flip the buffer so its ready to read
buffer.flip();
//create a texture
int id = glGenTextures();
//bind the texture
glBindTexture(GL_TEXTURE_2D, id);
//tell opengl how to unpack bytes
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
//set the texture parameters, can be GL_LINEAR or GL_NEAREST
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//upload texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
// Generate Mip Map
glGenerateMipmap(GL_TEXTURE_2D);
return new Texture(id);
}
Run Code Online (Sandbox Code Playgroud)
此方法假设一个简单的 Texture 类,如:
public class Texture{
private int id;
public Texture(int id){
this.id = id;
}
public int getId(){
return id;
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想要宽度,高度字段decoder.getWidth() decoder.getHeight()
会返回给你。
最后你创建一个纹理,如:
Texture texture = ClassName.loadTexture("/textures/texture.png");
Run Code Online (Sandbox Code Playgroud)
和
texture.getId();
Run Code Online (Sandbox Code Playgroud)
会给你相应的纹理ID。