smart-fun / smartGL

SmartGL is a Graphic Engine for creating Android Games and Apps. It is based on OpenGL and handles 2D Sprites and 3D Textured Objects.
Apache License 2.0
109 stars 24 forks source link

How to display a text? #3

Closed woshidag closed 7 years ago

woshidag commented 7 years ago

I want to display a text in smartGLView. How can I achieve this ?

smart-fun commented 7 years ago

Hello woshidag and thank you for using smartGL.

There are 2 ways to do this, the first one is without smartGL ^^ If you just want a 2D text on top of the surface, then you'd better to add a TextView on top of the SmartGLView (both in the same RelativeLayout for example)

The other way is using a Texture with a text in it, and then use that texture in a sprite or a 3D Object. To create that texture you'll need to draw the text in a bitmap. Here is an example on how to draw a text in a bitmap:

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 to create the texture and use it in a sprite:

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

Note that you don't have (must not) create the bitmap or texture at every frame! Create it once and use it. If you have several texts to write, I recommend to use one big texture and change UVs to split the Texture to be used by several faces (but this is another topic).

Arnaud.

woshidag commented 7 years ago

thank you.i use smartgl to show my robot's 2d map and robot pose.