实例说明:
在J2ME游戏开发中,经常需要一些说明性的文字,如游戏菜单,游戏帮助,或者游戏的内容简介,这些文字一般都很多,而手机屏幕的宽度有限,由于J2ME自身没有提供文字分行显示的方法,所以我们要自己写算法根据每行的宽度限制来自动调整每行文字的个数。效果如下图所示:
实现方法一:
我们可以自己写这样一个工具类,类中包含这样一个一个strspilt()方法,用户传入要绘制的字符串、字体、每行限制的宽度,然后根据算法,进行计算。具体算法如下代码:
StringTool工具类:
package com.main;
import java.util.Vector;
import javax.microedition.lcdui.Font;
/*
* 分割按字符串,字节数把字符串分组,支持中文
*/
public class StringTool {
public static Vector splitString(Font f, String str, int length) {
if (str == null)//判断传入的str是否为空
return null;
Vector result = new Vector();
char[] tempChar = str.toCharArray();//将传入的字符串转为字符数组
int size = 0;//记录每一行的宽度度
/*
* 每次循环,取出字符数组中的每一个字符并得到其宽度进行累加,
* 累加一个字符后,将累加的结果size与每行限制的宽度进行比较,大于或等于的情况下就换行,
* 或者取出的字符为转义字符\n的时候,就直接换行*/
StringBuffer sb = new StringBuffer() ;
if (sb.length() > 0)
result.addElement(sb.toString());
for (int i = 0; i < tempChar.length; i++) {
size += f.charWidth(tempChar[i]);
if (size >= length || tempChar[i] == '\n') {
result.addElement(sb.toString());
sb = new StringBuffer();
size = f.charWidth(tempChar[i]);
if (tempChar[i] != '\n') {
sb.append(tempChar[i]);
}
}else {
sb.append(tempChar[i]);
}
}
return result;
}
}
MainClass类:
package com.main;
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class MainClass extends MIDlet {
public MainClass() {
Display.getDisplay(this).setCurrent(new MainCanvas());
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
}
}
MainCanva类:
package com.main;
import java.util.Vector;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.xml.parsers.FactoryConfigurationError;
public class MainCanvas extends Canvas {
//需要换行的字符串
String str="《植物大战僵尸》[1]是一款极富策略性的小游戏,可怕的僵尸即将入侵," +
"唯一的防御方式就是栽种植物。此游戏集成\n了即时战略、塔防御战和卡片收集等" +
"要素、游戏的内容就\n是:玩家控制\n植物,抵御僵尸的进攻,保护这片草坪。" +
"独特的五种游戏模式:冒险,迷你,益智,生存,花园。多达50个的冒险" +
"模式关卡设定,从白天到夜晚,从房顶到游泳池,场景变化多样。 ";
/*
* 三种字体,分别为小字体,中字体,大字体
*/
Font smallfont=Font.getFont(Font.FACE_MONOSPACE,Font.STYLE_PLAIN,Font.SIZE_SMALL);
Font mediumfont=Font.getFont(Font.FACE_MONOSPACE,Font.STYLE_PLAIN,Font.SIZE_MEDIUM);
Font lagerfont=Font.getFont(Font.FACE_MONOSPACE,Font.STYLE_PLAIN,Font.SIZE_LARGE);
public int SW;//每行所限制的字符串的宽
public Vector v;//生成一个容器,把字符串分割的每一行存储到Vector容器中
public MainCanvas(){
this.setFullScreenMode(true);//设置支持全屏
SW=this.getWidth();
v=StringTool.splitString(smallfont, str, SW);
}
//遍历这个Vector,调用g.drawString来显示字符串。需要在y坐标上累计字体的高度。
protected void paint(Graphics g) {
g.setColor(0xffff0000);
for(int i=0;i<v.size();i++){
String str=(String) v.elementAt(i);
int a=g.getFont().getHeight();
g.drawString(str,0,i*a,20);
}
}
}