在Android中使用Libgdx的过程中,有时候会遇到这样的需要, 后端返回给我们的是html tag,比如如下:
<p><i>italic </i><b>bold <i>italic+bold <u>italic+bold+un</u></i></b></p>

对于以上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 <= 0 ? tv.getMeasuredHeight() : textureHeight;
tv.layout(((int) paddingLeft), ((int) (0 + paddingTop)),
(int) (width - paddingRight), ((int) (height - paddingBottom)));
tv.buildDrawingCache();
final Bitmap bitmap = tv.getDrawingCache();
Texture tex = new Texture(bitmap.getWidth(), bitmap.getHeight(), Pixmap.Format.RGBA8888);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tex.getTextureObjectHandle());
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
bitmap.recycle();
return tex;
}
}
文章评论