在椭圆上绘制字符串

时间:2012-10-10 03:53:46

标签: java swing awt ellipse drawstring

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

2 个答案:

答案 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);

您必须使用offsetXoffsetY的具体值来使其看起来不错。

如果您想要更加漂亮并且让它drawString根据所使用的字体自动调整位置,请查看thisFontMetrics类。您希望offsetXoffsetY根据所绘制字符的宽度和高度等因素而变化。

答案 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]);