Skip to content

Texts as Textures

Arnaud Guyon edited this page Apr 18, 2017 · 1 revision

The simplest way to display a text on top of a SmartGLView is to put a TextView on top of the SmartGLView (both in the same RelativeLayout for example).

But this is also possible to use a text as a Texture for a Sprite or a 3D Object. To do this the text must be first written in a Bitmap, and then a Texture must be created with this Bitmap.

Here is an example on how to create a Bitmap from a Text:

private Bitmap createBitmapFromText(String text) {
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setTextSize(20);
    paint.setColor(0xFF112233);
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);
    int width = bounds.right - bounds.left;
    int height = bounds.bottom - bounds.top;
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    if (bitmap != null) {
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(0xFFdd8833);
        canvas.drawText(text, -bounds.left, -bounds.top, paint);
    }
    return bitmap;
}

Then this bitmap can be used as Texture, on a Sprite for example:

Bitmap bitmapText = createBitmapFromText("Hello World");
if (bitmapText != null) {
    Texture texture = new Texture(bitmapText);
    mySprite.setTexture(texture);
}

Note that the bitmap and texture have to be created only once, then they are used by the sprite. The bitmap will be released when the OpenGL engine will generate the OpenGL Texture (so do not release it by yourself).

Clone this wiki locally