服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

如何在j2me的低级界面中轻松实现各种文字的自然分行显示

做游戏的时候,特别是在一些对话比较多的情况下,如rpg游戏,常常遇到文字的断行显示问题
如何做到不管如何变化文字,都能够比较好地显示呢,下面有一个函数可以对文字进行分行,然后就可以一行行地打印了

第四个参数主要是对像英语这样多个字母组成一个单词的语言而设置的,因为像英语你不能把一个单词一分为二成两行的,可以传入一些分词的标志,如空格、标点符号什么的,如“ ,.?!”
中文没有关系
但是日文我也闹不大清楚,不知道它是怎么分词的,是和中文一样,还是和英文一样

  /**@todo 对一段文字进行分行,这种分行是针对于某个字体的
   * @author efei
   * @param strsource string 待分行的字符串
   * @param font font 使用的字体
   * @param width int 分行后需要满足的宽度
   * @param strsplit string 断词判断字符,如空格和一些标点符号。中文不需要断词,则传空字符串
   * @return vector
   */
  public vector getsubsection(string strsource,font font
                              ,int width,string strsplit){
     vector vector = new vector();
     string temp=strsource;
     int i,j;
     int lastlength = 1;
     int step = 0;
     try{
         while (!temp.equals("")) {
           i=temp.indexof("/n");
           if(i>0){
      if(font.stringwidth(temp.substring(0,i-1)) >= width){
               i = -1;
             }
           }
           if(i==-1){
             if(lastlength>temp.length()){
               i = temp.length();
             }else{
               i = lastlength;
               step = font.stringwidth(temp.substring(0, i)) > width ? -1 : 1;
               //得到临界点
               if(i<temp.length()){
                 while (! (font.stringwidth(temp.substring(0, i)) <= width
                           && font.stringwidth(temp.substring(0, i + 1)) > width)) {
                   i = i + step;
                   if (i == temp.length())
                     break;
                 }
               }
             }
             //断词,如果需要的话
             if(!strsplit.equals("")){
               j = i; //把初始值记录下来,是因为有可能出现一种情况,这种情况就是这一行只有这么一个单词,会一直搜索到头
               if (i < temp.length()) {
                 while (strsplit.indexof(temp.substring(i-1,i))==-1) {
                   i--;
                   if (i == 0) {
                     i = j; //恢复
                     break;
                   }
                 }
               }
             }
           }
           lastlength = i;
           vector.addelement(temp.substring(0, i));
           if (i == temp.length()) {
             temp = "";
           }
           else{
             temp = temp.substring(i);
             if (temp.substring(0, 1).equals("/n")) {
               temp = temp.substring(1);
             }
           }
         }
     }catch(exception e)
     {
       system.out.println("getsubsection:"+e);
     }
     return vector;
   }


使用示例:
int gintlineheight = 15;//全局变量,行高
int gintbeginindex = 0;//全局变量,在keypressed里改变它的值,便可以实现上下翻页

string str = "方便起见,可以定义一个行高作为全局变量,这样比较好,写个简单的例子:"
vector vector  = getsubsection(str,font.getdefaultfont(),getwidth(),"");

for(int i=gintbeginindex;i<vector.size();i++){
  g.drawstring((string)vector.elementat(i),0,gintlineheight*i,0);
  if((i-mintbeginindex+1)*gintlineheight>getheight())break;
}
vector = null;

扫描关注微信公众号