本文讲述如何在游戏开发中实现类似于打字的功能,其实原理和前面讲述的文字滚屏差别不大,主要还是利用Timer和Canvas提供的函数。
我们的目的是把几个字按照顺序和一定的时间间隔打印在屏幕上,这就要求我们计算好文字的宽度和具体打印的位置。例如这样一个数组
private final String[] content = { "hello ", "world ", "who ", "are ","you ", "?" };
我使用的办法是计算它们的相对距离,这样我用一个int类型的数组来存储这些数值。
private int[] slen = new int[content.length];
slen[0]存储字开始打印的位置,这里我设置为10,slen[1]则存储开始位置与hello这个字的长度之和作为下个单词world的开始位置,依次类推。
private void initSlen()
{
int temp = 10;
for (int i = 0; i < content.length; i++)
{
slen[i] = temp;
temp = temp + font.stringWidth(content[i]);
}
}
注意这里并没有考虑屏幕宽度的因素,如果你要显示多行的话应该考虑到屏幕的宽度,调整你的算法。
在paint()方法里面我们就按照得到的坐标位置进行绘画
protected void paint(Graphics arg0)
{
if (first)
{
arg0.setColor(128, 0, 128);
arg0.fillRect(0, 0, getWidth(), height);
first = false;
}
arg0.setColor(255, 255, 255);
arg0.setFont(font);
arg0.drawString(content[i], slen[i], height / 2, Graphics.LEFT
| Graphics.TOP);
}
程序并不复杂,下面给出源代码。
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class TypeMIDlet extends MIDlet
{
private Display display;
private TypeCanvas typeCanvas;
protected void startApp() throws MIDletStateChangeException
{
display = Display.getDisplay(this);
typeCanvas = new TypeCanvas();
display.setCurrent(typeCanvas);
}
protected void pauseApp()
{
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException
{
}
}
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
public class TypeCanvas extends Canvas
{
private Timer timer = new Timer();
private int i = 0;
private boolean first = true;
private int height = getHeight();
Font font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD,
Font.SIZE_MEDIUM);
private final String[] content = { "hello ", "world ", "who ", "are ",
"you ", "?" };
private int[] slen = new int[content.length];
public TypeCanvas()
{
super();
initSlen();
TypeTask tt = new TypeTask();
timer.schedule(tt, 300, 300);
}
protected void paint(Graphics arg0)
{
if (first)
{
arg0.setColor(128, 0, 128);
arg0.fillRect(0, 0, getWidth(), height);
first = false;
}
arg0.setColor(255, 255, 255);
arg0.setFont(font);
arg0.drawString(content[i], slen[i], height / 2, Graphics.LEFT
| Graphics.TOP);
}
private void initSlen()
{
int temp = 10;
for (int i = 0; i < content.length; i++)
{
slen[i] = temp;
temp = temp + font.stringWidth(content[i]);
}
}
private class TypeTask extends TimerTask
{
public void run()
{
if (i < content.length - 1)
{
repaint();
i++;
} else
{
timer.cancel();
}
}
}
}