JavaMe開(kāi)發(fā):繪制可自動(dòng)換行文本
【問(wèn)題描述】
JavaMe Graphics類中的drawString不支持文本換行,這樣繪制比較長(zhǎng)的字符串時(shí),文本被繪制在同一行,超過(guò)屏幕部分的字符串被截?cái)嗔?。如何使繪制的文本能自動(dòng)換行呢?
【分析】
drawString無(wú)法實(shí)現(xiàn)自動(dòng)換行,但可以實(shí)現(xiàn)文本繪制的定位。因此可考慮,將文本拆分為多個(gè)子串,再對(duì)子串進(jìn)行繪制。拆分的策略如下:
1 遇到換行符,進(jìn)行拆分;
2 當(dāng)字符串長(zhǎng)度大于設(shè)定的長(zhǎng)度(一般為屏幕的寬度),進(jìn)行拆分。
【步驟】
1 定義一個(gè)String和String []對(duì)象;
- private String info;
- private String info_wrap[];
2 實(shí)現(xiàn)字符串自動(dòng)換行拆分函數(shù)
StringDealMethod.java
- package com.token.util;
- import java.util.Vector;
- import javax.microedition.lcdui.Font;
- public class StringDealMethod {
- public StringDealMethod()
- {
- }
- // 字符串切割,實(shí)現(xiàn)字符串自動(dòng)換行
- public static String[] format(String text, int maxWidth, Font ft) {
- String[] result = null;
- Vector tempR = new Vector();
- int lines = 0;
- int len = text.length();
- int index0 = 0;
- int index1 = 0;
- boolean wrap;
- while (true) {
- int widthes = 0;
- wrap = false;
- for (index0 = index1; index1 < len; index1++) {
- if (text.charAt(index1) == '\n') {
- index1++;
- wrap = true;
- break;
- }
- widthes = ft.charWidth(text.charAt(index1)) + widthes;
- if (widthes > maxWidth) {
- break;
- }
- }
- lines++;
- if (wrap) {
- tempR.addElement(text.substring(index0, index1 - 1));
- } else {
- tempR.addElement(text.substring(index0, index1));
- }
- if (index1 >= len) {
- break;
- }
- }
- result = new String[lines];
- tempR.copyInto(result);
- return result;
- }
- public static String[] split(String original, String separator) {
- Vector nodes = new Vector();
- //System.out.println("split start...................");
- //Parse nodes into vector
- int index = original.indexOf(separator);
- while(index>=0) {
- nodes.addElement( original.substring(0, index) );
- original = original.substring(index+separator.length());
- index = original.indexOf(separator);
- }
- // Get the last node
- nodes.addElement( original );
- // Create splitted string array
- String[] result = new String[ nodes.size() ];
- if( nodes.size()>0 ) {
- for(int loop=0; loop<nodes.size(); loop++)
- {
- result[loop] = (String)nodes.elementAt(loop);
- //System.out.println(result[loop]);
- }
- }
- return result;
- }
- }
3 調(diào)用拆分函數(shù),實(shí)現(xiàn)字符串的拆分
- int width = getWidth();
- Font ft = Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_BOLD,Font.SIZE_LARGE);
- info = "歡迎使用!\n"
- +"1 MVC測(cè)試;\n"
- +"2 自動(dòng)換行測(cè)試,繪制可自動(dòng)識(shí)別換行的字符串。\n";
- info_wrap = StringDealMethod.format(info, width-10, ft);
4 繪制字符串
- graphics.setColor(Color.text);
- graphics.setFont(ft);
- for(int i=0; i<info_wrap.length; i++)
- {
- graphics.drawString(info_wrap[i], 5, i * ft.getHeight()+40, Graphics.TOP|Graphics.LEFT);
- }
繪制的效果如圖1所示:
圖1 自動(dòng)換行字符串繪制效果
原文鏈接:http://blog.csdn.net/tandesir/article/details/7541403
【系列文章】