Android使用Libgdx渲染Html标签

在Android中使用Libgdx的过程中,有时候会遇到这样的需要, 后端返回给我们的是html tag,比如如下:

italic bold italic+bold italic+bold+un

对于以上Html tag,如果使用android自带的控件TextView可以通过setText(Html.from(“”))的方式直接设置显示内容。效果如下:

但是在Libgdx中并没有提供相应的控件实现这种效果。所以需要转换一下思路, 具体的实现思路就是先将Html文本内容设置到TextView,然后对TextView截图获取Bitmap对象,然后将Bitmap对象通过OpenGL转化为Texture对象,有了Texture对象就可以在Libgdx中渲染了。

具体实现如下:

package com.ef.smallstar.libgdx.util;

import android.graphics.Bitmap;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.ef.smallstar.EFApplication;

/**
 * Created by Danny 姜 on 17/8/10.
 */

public class GdxHtmlUtils {

    public static Texture fromString(String string, int textSize) {

        return fromString(string, textSize, 0, 0);
    }

    public static Texture fromString(String string, int textSize,
                                     float textureWidth, float textureHeight) {
        return fromString(string, textSize, textureWidth, textureHeight, 0, 0, 0, 0);
    }

    public static Texture fromString(String string, int textSize,
                                     float textureWidth, float textureHeight,
                                     float paddingLeft, float paddingTop,
                                     float paddingRight, float paddingBottom) {
        TextView tv = new TextView(EFApplication.getInstance());
        tv.setGravity(Gravity.CENTER);

        tv.setText(Html.fromHtml(string));
        tv.setTextSize(textSize);

        tv.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        float width = textureWidth <= 0="" ?="" tv.getmeasuredwidth()="" :="" texturewidth;="" float="" height="textureHeight" 

:http://www.linuxidc.com/Linux/2017-10/147676.htm