0

但是,我对时钟的输出感到满意-我不确定如何正确对齐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 提供了找到解决方案的正确步骤。

4

2 回答 2

4

如果您想象将字符串包含在一个框内,则传入的 x 和 y 值drawString指定框的左下角。

我会这样修改该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);

您必须使用特定的值offsetXoffsetY使它看起来不错。

如果你想变得更漂亮,让它drawString根据使用的字体自动调整位置,看看这个FontMetrics类。您需要根据正在绘制的字符的宽度和高度以及诸如此类的东西来制作offsetX和改变。offsetY

于 2012-10-10T04:12:52.197 回答
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]);
于 2012-10-10T04:59:34.633 回答