|
|
| 作者:Jagie 来源:www.javaresearch.org 发布时间:2006-02-27 15:35:36.953 |
|
|
正文
在J2ME游戏中,我们通常要在一个指定的矩形区域内绘制一段文本,比如游戏介绍和指导信息等。每次都要重复写代码实在很烦,这里给出一个简单的折行文本的绘制方法,希望能省去你的重复劳动,不过如果你想实现按键翻页的话,那还需要你自己再加点代码:)
-
- import javax.microedition.lcdui.Font;
- import javax.microedition.lcdui.Graphics;
-
- /**
- * GraphicsUtil
- *
- * @author Jagie
- *
- */
- public class GraphicsUtil {
- /**
- * 在制定矩形内,绘制折行文本,超出矩形范围的字符不显示
- * @param src 文本字串
- * @param g Graphics对象
- * @param x 矩形左上角x坐标
- * @param y 矩形左上角y坐标
- * @param w 矩形宽度
- * @param h 矩形高度
- * @param leftMargin 左边矩
- * @param topMargin 上边距
- * @param isVTight 行间距是否紧凑
- * @param fontColor 文字颜色
- * @param font 绘制所用字体
- */
- public static final void drawWrapString(String src, Graphics g, int x, int y, int w,
- int h, int leftMargin,int topMargin, boolean isVTight, int fontColor, Font font) {
- g.setFont(font);
- g.setColor(fontColor);
- int count = src.length();
- int curCharIndex = 0;
- int curX = x+leftMargin;
- int curY = y+topMargin;
- int vDelta=font.getHeight();
- if(isVTight){
- vDelta=font.getBaselinePosition();
- }
- while (curCharIndex < count) {
- char c = src.charAt(curCharIndex);
- if (c == '\n') {
- curX = x+leftMargin;
- curY += vDelta;
- curCharIndex++;
- continue;
- } else if (c == '\t') {
- // 相当于2个空格
- curX += font.charWidth(' ')*2;
- curCharIndex++;
-
- continue;
- }
-
- if (curX + font.charWidth(c) < x + w) {
-
- g.drawChar(c, curX, curY, Graphics.LEFT | Graphics.TOP);
- curCharIndex++;
- curX += font.charWidth(c);
-
- } else {
- //考虑换行
- if(curY+2*font.getBaselinePosition()<y+h){
- curY += vDelta;
- curX = x+leftMargin;
- g.drawChar(c, curX, curY, Graphics.LEFT | Graphics.TOP);
- curCharIndex++;
- curX += font.charWidth(c);
- }else{
- break;
- }
- }
- }
- }
- }
-
比如一下代码:
-
- public void paint(Graphics g) {
- g.setColor(0);
- g.fillRect(0, 0, w, h);
- g.setColor(0x00ff00);
- Font f= Font.getFont(
- Font.FACE_SYSTEM, Font.STYLE_PLAIN,
- Font.SIZE_SMALL);
- g.setFont(f);
- g.drawRect(10,25,w-20,100);
- GraphicsUtil
- .drawWrapString(
- " 大多数的人在作决定时都只考虑眼前而不顾未来,结果快乐没得到却得到痛苦,事实上人世间一切有意义的事若想成功,那就必须忍受一时的痛苦。你必须熬过眼前的恐惧和引诱,按照自己的价值观或标准面把目光放在未来。你要记住,任何事都不会使我们痛苦,而真正使我们痛苦的是对于痛苦的恐惧,同样的道理,也没有任何事会使我们快乐,而真正能使 我们快乐的是对于快乐的把握。",
- g,10, 25, w-20, 100,6,6, false,0xffffff,f);
- }
-
的绘制效果如下图:
作者简介 陈万飞,网名Jagie,培训师,爱好java技术.可通过chen_cwf@163.com与他联系
|
|
|