android - 在 OpenGL ES 中绘制文本

标签 android opengl-es text-rendering

我目前正在为 Android 平台开发一个小型 OpenGL 游戏,我想知道是否有一种简单的方法可以在渲染帧的顶部渲染文本(例如带有玩家得分的 HUD 等)。文本也需要使用自定义字体。

我看到了一个使用 View 作为叠加层的示例,但我不知道是否要这样做,因为我可能希望稍后将游戏移植到其他平台。

有什么想法吗?

最佳答案

将文本渲染到纹理比 Sprite Text 演示看起来更简单,基本思想是使用 Canvas 类渲染到 Bitmap,然后将 Bitmap 传递给 OpenGL 纹理:

// Create an empty, mutable bitmap
Bitmap bitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_4444);
// get a canvas to paint over the bitmap
Canvas canvas = new Canvas(bitmap);
bitmap.eraseColor(0);

// get a background image from resources
// note the image format must match the bitmap format
Drawable background = context.getResources().getDrawable(R.drawable.background);
background.setBounds(0, 0, 256, 256);
background.draw(canvas); // draw the background to our bitmap

// Draw the text
Paint textPaint = new Paint();
textPaint.setTextSize(32);
textPaint.setAntiAlias(true);
textPaint.setARGB(0xff, 0x00, 0x00, 0x00);
// draw the text centered
canvas.drawText("Hello World", 16,112, textPaint);

//Generate one texture pointer...
gl.glGenTextures(1, textures, 0);
//...and bind it to our array
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

//Create Nearest Filtered Texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

//Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);

//Use the Android GLUtils to specify a two-dimensional texture image from our bitmap
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

//Clean up
bitmap.recycle();

关于android - 在 OpenGL ES 中绘制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1339136/

相关文章:

java - 更改 TextView 中特定单词的颜色

java - Firebase Realtime 在类 java.lang.CharSequence 上找不到要序列化的属性

Android OpenGL ES,形状未在设备上显示,但在模拟器上工作正常?

android:双指放大/缩小

css - “Lato”字体在 safari 中呈现奇怪,而不是在 chrome 或 firefox 中

ios - iOS 和 Mac 之间的文本渲染不一致

android - 当我复制一些 TableRows 时,“渲染布局无限循环或无限递归时预览超时”

ios - 使用 glReadPixels 读取纹理字节?

browser - 为什么像 Chrome 这样的跨平台应用程序不使用 FreeType 来呈现文本?

android - 从容器中删除所有 fragment