public static final int LEFT = 1; //居左
public static final int CENTER = 1 << 1; //居中
public static final int RIGHT = 1 << 2; //居右
public static final int TOP = 1 << 3; //居上
public static final int MIDDLE = 1 << 4; //居中
public static final int BOTTOM = 1 << 5; //居下
public static final int FONT_HEIGHT = 11; //字体高度
/**
* 绘制居中字符串
* @param g Graphics - 画刷
* @param str String - 绘制字符串
* @param rectX int - 矩形左上角X
* @param rectY int - 矩形左上角Y
* @param rectWidth int - 矩形宽度
* @param rectHeight int - 矩形高度
* @param align int - 类型
* @return boolean - 是否成功
*/
public static boolean drawAlignStr(
Graphics g, String str,
int rectX, int rectY,
int rectWidth, int rectHeight,
int align) {
if (str == null || g == null) {
return false;
}
//获得字体
Font currentFont = g.getFont();
//绘制坐标
int x = 0;
int y = 0;
//字符串宽度与高度
int strWidth = currentFont.stringWidth(str);
int strHeight = FONT_HEIGHT; //currentFont.getHeight() 不能使用
//矩形右边和下边坐标
int rectRight = rectX + rectWidth;
int rectBottom = rectY + rectHeight:
if ((align & CENTER) == CENTER) {
x = (rectWidth >> 1) - (strWidth >> 1) + rectX;
} else if ((align & LEFT) == LEFT) {
x = rectX;
} else if ((align & RIGHT) == RIGHT) {
x = rectWidth - strWidth + rectX;
}
//如果字符串宽度超出Rect,居左显示(错误处理也可以写在这) return false;
x = x < rectX ? rectX : x;
x = x > rectRight ? rectX : x;
if ((align & MIDDLE) == MIDDLE) {
y = (rectHeight >> 1) - (strHeight >> 1) + rectY;
} else if ((align & TOP) == TOP) {
y = rectY;
} else if ((align & BOTTOM) == BOTTOM) {
y = rectHeight - strHeight + rectY;
}
//如果字符串高度超出Rect,居上显示(错误处理也可以写在这) return false;
y = y < rectY ? rectY : y;
y = y > rectBottom ? rectY : y;
//裁减区
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, x, y, Graphics.LEFT | Graphics.TOP);
g.setClip(oldClipX, oldClipY, oldClipWidth, oldClipHeight);
return true;
}
|