libgdx学习记录9——FreeType,ttf中文显示

前面讲到使用Hireo创建的BitmapFont以显示中文字体。这种方式效率很高,当所要显示的字的总数较少,并且大小比较固定时,可以采用这种方式。

但是这种也有弊端:

(1)字体大小不能随意设置,当放大时就会变形。

(2)当所要显示的字总数较多或者经常变化时,会很麻烦。

libgdx对中文的支持不太好,也是很多人转向其他引擎的一个原因。幸好,其扩展模块中的FreeType能够通过ttf字体来实现随意中文显示。

FreeType是libgdx的扩展模块,创建项目时需要添加对应的jar包和对应的动态运行库。

core工程lib中加入gdx-freetype.jar。

desktop工程lib中加入gdx-freetype-natives.jar。

android工程中lib加入gdx-freetype.jar,并将armeabi和armeabi-v7a中的libgx-freetype.so文件添加到对应的目录中。

三个工程中分别将对应的jar包添加到Refrenced Libraries中。

环境配置完成,具体事例如下:

 1 package com.fxb.freetype;
 2 
 3 import com.badlogic.gdx.ApplicationListener;
 4 import com.badlogic.gdx.Gdx;
 5 import com.badlogic.gdx.graphics.Color;
 6 import com.badlogic.gdx.graphics.GL10;
 7 import com.badlogic.gdx.graphics.g2d.BitmapFont;
 8 import com.badlogic.gdx.graphics.g2d.SpriteBatch;
 9 
10 import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
11 import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeBitmapFontData;
12 
13 
14 public class FreeType implements ApplicationListener{
15 
16     BitmapFont[] font;
17     //FreeTypeBitmapFontData fontData;
18     FreeTypeFontGenerator generator;    
19     SpriteBatch batch;
20     
21     @Override
22     public void create() {
23         // TODO Auto-generated method stub
24         batch = new SpriteBatch();
25         font = new BitmapFont[3];
26         Color[] colors = { Color.RED, Color.BLUE, Color.GREEN };
27         for( int i=0; i<3; ++i ){
28             generator = new FreeTypeFontGenerator( Gdx.files.internal( "data/" + (i+1) + ".ttf" ) );
29             font[i] = generator.generateFont( 25, FreeTypeFontGenerator.DEFAULT_CHARS+"今天是个好日子,大家心情都很", false );
30             font[i].setColor( colors[i] );
31             generator.dispose();
32         }
33 
34         //fontData = generator.generateData( 25, FreeTypeFontGenerator.DEFAULT_CHARS+"今天是个好日子,大家心情都很", false );
35     }
36 
37     @Override
38     public void resize(int width, int height) {
39         // TODO Auto-generated method stub
40         
41     }
42 
43     @Override
44     public void render() {
45         // TODO Auto-generated method stub
46         
47         Gdx.gl.glClearColor( 1, 1, 1, 1 );
48         Gdx.gl.glClear( GL10.GL_COLOR_BUFFER_BIT );
49         
50         batch.begin();
51         for( int i=0; i<3; ++i ){
52             font[i].drawMultiLine( batch, "今天是个好日子,\n大家心情都很好\nVery Good! 20140521!!", 120, 100*(3-i) );
53         }
54         batch.end();
55     }
56 
57     @Override
58     public void pause() {
59         // TODO Auto-generated method stub
60         
61     }
62 
63     @Override
64     public void resume() {
65         // TODO Auto-generated method stub
66         
67     }
68 
69     @Override
70     public void dispose() {
71         // TODO Auto-generated method stub
72         batch.dispose();
73     }
74     
75 }

运行效果:

文中用到了3个ttf文件,1.ttf为娃娃体,2.ttf为幼圆,3.ttf为行楷。

posted @ 2014-05-21 12:32  丛林小阁楼  阅读(3397)  评论(0编辑  收藏  举报