2013-08-02 32 views
0

如何在我知道線座標時在java中平行於一條線繪製字符串? 下面是我的代碼到目前爲止,x1,y1和x2,y2代表行的座標。 (文本必須是平行和對線的中心)平行於一條線的Java drawString

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>); 
+0

這不回答你的問題,但你不應該使用'setTransform'來覆蓋現有的變換。該方法只是爲了將早期狀態恢復到Graphics2D對象。 – resueman

+0

謝謝!你是絕對正確的。我在想什麼...... D – sanjan

回答

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的幫助

0

黃褐色(THETA)=斜率=(Y2-Y1)/(X2-X1)

THETA = ATAN(斜率)

暗示,use

at.rotate(Math.toRadians(theta)) 

至於

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

x,y是字符串的leftmost character的座標。

+0

所以我做我的代碼如:(Math.abs(x2-x1)> 0)雙斜率=(y2-y1)/Math.abs(x2-x1) ; double tan = Math.atan(slope); at.rotate(Math.toRadians(tan));}我是否正確? – sanjan

+0

是的,儘管你可以在一個聲明中做所有事情:) – rocketboy