高度标尺上的Java图形值会切断字符串
我正在根据0到3公里的范围创建一个高度刻度,以公里为单位,其中3公里为红色,0为蓝色,因此在蓝色和红色之间创建一个刻度 我成功地制作了比例,现在我想在比例上放置文本,以大致显示比例上每25像素的高度:高度标尺上的Java图形值会切断字符串,java,Java,我正在根据0到3公里的范围创建一个高度刻度,以公里为单位,其中3公里为红色,0为蓝色,因此在蓝色和红色之间创建一个刻度 我成功地制作了比例,现在我想在比例上放置文本,以大致显示比例上每25像素的高度: private void drawHeightScale(Graphics2D g2d) { // Scale meter dimensions int scaleHeight = 300; int scaleWidth = 50; // Scale meter
private void drawHeightScale(Graphics2D g2d) {
// Scale meter dimensions
int scaleHeight = 300;
int scaleWidth = 50;
// Scale meter position
int x = getBoss().getWidth() - (scaleWidth + 10);
int y = getBoss().getHeight() - (scaleHeight + 10);
// the maximum allowed height
double max = 3;
// the current height for scale drawing
double current = max;
// The color ratio
double ratio = 255 / max;
// Current Y to draw scale line color
int currentY = y;
// How much to decrease from height every time starting from height max
float decreaseRatio = (float) (max / 255);
// setting font for the text on the meter
Font font = new Font("Arial", Font.BOLD, 10);
g2d.setFont(font);
// Iterate through scale height to draw each color line to create a meter
for (int i = 0; i < scaleHeight; i++) {
// Red value
float r = (float) (current * ratio);
// Blue value
float b = 255 - r;
// Draw meter
g2d.setColor(new Color(r / 255, 0, b / 255));
g2d.fillRect(x, currentY, scaleWidth, 1);
// start drawing text
g2d.setColor(Color.WHITE);
// Do it every 50px
if (i % 50 == 0) {
String n = formater.format(current) + " Km";
g2d.drawString(n, x + (scaleWidth / 2) - g2d.getFontMetrics().stringWidth(n) / 2, y + i);
}
// Decrease
if (current >= decreaseRatio ) {
current -= decreaseRatio ;
}
// Next y
currentY++;
}
}
这就是我得到的:
文本的高度被截断了,我真的看不出原因,除了API中的一些东西
我哪里做错了什么?你正在画一个矩形,然后是一个文本。rect正在绘制文本
尝试在绘制文本后先绘制矩形…您正在绘制文本后的矩形。rect正在绘制文本
尝试在绘制文本后先绘制矩形…看起来文本开始在正确的位置绘制,但它只是从下到上绘制文本,但不明白为什么向下按会切断文本,这是因为在字符串标签上绘制红色/蓝色像素行。在两个不同的for循环中分离这两个操作(首先绘制彩色线,然后绘制字符串),它应该可以解决问题看起来文本开始在正确的位置绘制,但它只是从下到上绘制文本,但我不明白,如果我向下推它,它为什么会切断文本,这是因为你在字符串标签上画的是红/蓝像素行。在两个不同的for循环中分离这两个操作(首先绘制彩色线,然后绘制字符串),应该可以解决问题
g2d.drawString(n, x + (scaleWidth / 2) - g2d.getFontMetrics().stringWidth(n) / 2, (y + 3) + i);