程序实现滚动文字效果

原文地址: J2ME下实现滚动文字效果

J2ME下实现滚动文字也很简单,就是基于剪裁区的应用

看一下效果:

来看一下代码:

private int tipStringPos = SCREEN_WIDTH; //当前字符串左边的位置
private int tipStringSpeed = 2; 
//字符串移动速度
private static final int TIPSTR_LEFT = 5 – 5; 
//左边消失绘制坐标
private static final int TIPSTR_RIGHT = 123 + 5; 
//右边出现绘制坐标

private static final int FONT_HEIGHT = 11; //字体高度 font.getHeight() 不准确

/**
 * @param Graphics g – 画刷
 * @param String str – 所画字符串
 * @param int height – 字符串高度
 * @param int rectX – 剪裁区顶点X坐标
 * @param int rectY – 剪裁区顶点Y坐标
 * @param int rectWidth – 剪裁区宽度
 * @param int rectHeight – 剪裁区高度
 */

private void drawTipString(Graphics g, String str, int height, 
            
int rectX, int rectY, int rectWidth, int rectHeight
) {
    
int strWidth = g.getFont().stringWidth(str
);
    
int strHeight = FONT_HEIGHT
;
    
    
tipStringPos -= tipStringSpeed
;
    if (
tipStringPos + strWidth < TIPSTR_LEFT
) {
        
tipStringPos = TIPSTR_RIGHT
;
    }

    //裁减区
    
int oldClipX = g.getClipX
();
    
int oldClipY = g.getClipY
();
    
int oldClipWidth = g.getClipWidth
();
    
int oldClipHeight = g.getClipHeight
();

    g.setClip(rectX, rectY, rectWidth, rectHeight);

    g.drawString(str, tipStringPos, height – strHeight / 2,
                 
Graphics.LEFT | Graphics.TOP
);
    
g.setClip(oldClipX, oldClipY, oldClipWidth, oldClipHeight
);
}