我对我的时钟输出感到满意,但是 - 我不确定如何正确对齐我的drawString
以查找应该出现在时钟每个刻度标记尖端的数字。
我希望有人能够为此展示正确的方法/公式。
private void drawTickMarks(Graphics2D g2)
{
double radius = this.faceRadius;
for (int secs = 0; secs <= 60; secs++)
{
double tickStart;
if (secs % 5 == 0)
tickStart = radius - 15;
else
tickStart = radius - 5;
tick = drawRadii(secs / 60.0, tickStart, radius);
if (secs % 5 == 0)
{
g2.setStroke(new BasicStroke(3));
g2.drawString(""+(secs/5),(int)tick.getX1()+(int)(tick.getX1()-tick.getX2()),
(int)tick.getY1()+(int)(tick.getY1()-tick.getY2()));
}
else
g2.setStroke(new BasicStroke(1));
g2.setColor(Color.WHITE);
g2.draw(tick);
}
}
感谢Thinhbk提供有效且正确的代码解决方案和Jon W,以便为解决方案提供正确的步骤。
答案 0 :(得分:4)
如果您想象框中包含的字符串,则传递到drawString
的x和y值指定框的左下角。
我会修改drawString
行:
String number = ""+(secs/5);
int xLocation = (int)tick.getX1()+(int)(tick.getX1()-tick.getX2());
int yLocation = (int)tick.getY1()+(int)(tick.getY1()-tick.getY2());
int offsetX = /*Insert some value here to shift the position of all the strings
along the x-axis. Make this an expression that contains number.length(),
so that two-digit numbers are shifted more than one digit numbers. */
int offsetY = /*Insert some value here to shift the position of all the strings along
the y-axis.*/
g2.drawString(number, xLocation + offsetX, yLocation + offsetY);
您必须使用offsetX
和offsetY
的具体值来使其看起来不错。
如果您想要更加漂亮并且让它drawString
根据所使用的字体自动调整位置,请查看this和FontMetrics
类。您希望offsetX
和offsetY
根据所绘制字符的宽度和高度等因素而变化。
答案 1 :(得分:2)
作为Jon W提供的解决方案的补充,我创建了一个计算偏移的方法,而IMO看起来很好。 (@Jon W:很抱歉没有为您的解决方案添加评论,因为它相当长。)
/**
* Calculate the offset *
* @param i
* @return array:
* 0: x offset
* 1: y offset
*/
private int[] calculateOffSet(int i) {
int[] val = new int[2];
int deflt = -12;
if(i == 12) {
val[0] = -15;
val[1] = 9;
}else if (i > 6) {
val[0] = deflt + i - 6 ;
val[1] = i ;
}else {
val[0] = deflt + i ;
val[1] = i + 6;
}
return val;
}
在你的代码中,只需调用它:
int xLocation = (int)tick.getX1()+(int)(tick.getX1()-tick.getX2());
int yLocation = (int)tick.getY1()+(int)(tick.getY1()-tick.getY2());
int[] offset = calculateOffSet((secs / 5));
g2.drawString(number, xLocation + offset[0], yLocation + offset[1]);