0

当我知道线坐标时,如何在java中绘制平行于线的字符串?下面是我到目前为止的代码,x1,y1 和 x2,y2 代表线的坐标。(文本必须平行并位于行的中心)

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>);
4

2 回答 2

0

tan(theta) = 斜率 = (y2-y1)/(x2-x1)

theta = atan(斜率)

这意味着,使用

at.rotate(Math.toRadians(theta))

至于

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

x,y 是字符串最左侧字符的坐标。

于 2013-08-02T13:21:28.217 回答
0

经过一番研究,

这就是我想出的

        //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);

感谢@rocketboy 和@resueman 的帮助

于 2013-08-03T07:09:49.783 回答