0

How to draw string in java parallel to a line when I know line coordinates? Below is my code so far, x1,y1 and x2,y2 represents the coordinates of line. (text has to be parallel and to the center of the line)

g.drawLine(x1, y1, x2, y2);

AffineTransform at = new AffineTransform();
at.rotate(<WHAT TO PUT HERE>);
g.setTransform(at);
g.drawString("My Text", <WHAT TO PUT HERE> , <WHAT TO PUT HERE>);
sanjan
  • 147
  • 1
  • 2
  • 6
  • This doesn't answer your question, but you shouldn't use `setTransform` to overwrite the existing transform with a new one. The method's just intended to restore an earlier state to the `Graphics2D` object. – resueman Aug 02 '13 at 13:20
  • Thanks! You're absolutely right. What was I thinking... :D – sanjan Aug 02 '13 at 13:48

2 Answers2

0

tan(theta) = slope = (y2-y1)/(x2-x1)

theta = atan(slope)

that implies,use

at.rotate(Math.toRadians(theta))

As for

g.drawString(String str, int x, int y)

x,y is the coordinate of the leftmost character of your string.

rocketboy
  • 9,573
  • 2
  • 34
  • 36
  • So I do my code like: if (Math.abs(x2-x1)>0){ double slope = (y2-y1)/Math.abs(x2-x1); double tan = Math.atan(slope); at.rotate(Math.toRadians(tan));} Am I correct? – sanjan Aug 02 '13 at 13:49
  • Yes, though you can do all that in a single statement :) – rocketboy Aug 02 '13 at 13:54
0

After some more research,

This is what I came up with

        //draw the line
        g.drawLine(x1, y1, x2, y2);

        //get center of the line
        int centerX =x1 + ((x2-x1)/2);
        int centerY =y1 + ((y2-y1)/2);

        //get the angle in degrees
        double deg = Math.toDegrees(Math.atan2(centerY - y2, centerX - x2)+ Math.PI);

        //need this in order to flip the text to be more readable within angles 90<deg<270
        if ((deg>90)&&(deg<270)){
            deg += 180;
        }

        double angle = Math.toRadians(deg);

        String text = "My text";
        Font f = new Font("default", Font.BOLD, 12);
        FontMetrics fm = g.getFontMetrics(f);
        //get the length of the text on screen
        int sw =  fm.stringWidth(text);

        g.setFont(f);
        //rotate the text
        g.rotate(angle, centerX, centerY);
        //draw the text to the center of the line
        g.drawString(text, centerX - (sw/2), centerY - 10); 
        //reverse the rotation
        g.rotate(-angle, centerX, centerY);

Thanks to @rocketboy and @resueman for the help

sanjan
  • 147
  • 1
  • 2
  • 6