MIDP中处理文字的换行

在情景类游戏中,需对文字进行处理以在手机屏幕正确换行显示。文章详细介绍了计算换行位置的方法,给出了计算换行位置的代码,还展示了为文字分行的代码,后续将介绍制作文字滚屏效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作者:禹俊 文章来源:www.sf.org.cn

在游戏中,尤其是情景类的游戏当中,往往需要大量情节介绍的文字。要在小小的手机屏幕上显示这些文字,就必须对这些文字进行处理,使其能正确的换行,显示在你想要显示的宽度的范围内。下面我就会详细的介绍如何处理文字的换行。

首先应该计算需要换行的位置。这里我们以文字需要显示的宽度linewd,和“\n”为换行的标志

static public int ChangLine(String str, Font font, int linewd, boolean fullword)
{ // 计算需要换行的位置 str:需要显示的文字 font:文字的字体 linewd:需要显示的宽度
int len = 0, wd = 0;
for (int i = 0; i < str.length(); i++)
{

if (str.charAt(i) == '\n')
{
if (i == 0)
return len + 1;
else
return len + 2;
}
wd += font.charWidth(str.charAt(i));
if (wd > linewd)
{
if (fullword)
{
for (int j = len; j >= 0; j--)
{
if (str.charAt(j) < 0x30 || str.charAt(j) >= 128)
{
len = j;
break;
}
}
}
return len + 1;
}
len = i;
}
return 0;
}

计算好位置后,就开始为文字分行。

static public void DoLine(String infostr, int len)

{ // 为字符串分行,以便于显示
String tmpStr;
Vector InfoLines = null;
InfoLines = new Vector();
int tmpint; //需要换行的位置
while (true)
{
tmpint = ChangLine(infostr, DefaultFont, len, false);
if (tmpint == 0)
{
InfoLines.addElement(infostr);
break;
}
else
{
if (infostr.charAt(tmpint - 1) == '\n')
tmpStr = infostr.substring(0, tmpint - 1);
else
tmpStr = infostr.substring(0, tmpint);

InfoLines.addElement(tmpStr);
infostr = infostr.substring(tmpint, infostr.length());

}
}
}

以上就是处理文字分行的代码。接下来我讲介绍程序中制作文字的滚屏效果。请关注后续文章

{ // 为字符串分行,以便于显示
String tmpStr;
Vector InfoLines = null;
InfoLines = new Vector();
int tmpint; //需要换行的位置
while (true)
{
tmpint = ChangLine(infostr, DefaultFont, len, false);
if (tmpint == 0)
{
InfoLines.addElement(infostr);
break;
}
else
{
if (infostr.charAt(tmpint - 1) == '\n')
tmpStr = infostr.substring(0, tmpint - 1);
else
tmpStr = infostr.substring(0, tmpint);

InfoLines.addElement(tmpStr);
infostr = infostr.substring(tmpint, infostr.length());

}
}
}

以上就是处理文字分行的代码。接下来我讲介绍程序中制作文字的滚屏效果。请关注后续文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值