2014-04-04 84 views
0

你如何獲得要旋轉的字符串? (但不是一直旋轉,只是在一個角度)? 我嘗試使用Graphics2D,但找不到旋轉的方法。還是需要手動旋轉它?此外,如果更容易,我可以使用LWJGL,但目前我沒有與該庫有關的經驗。謝謝。Java圖形角度文本

回答

2

有很多方法可以實現這一目標。

這個例子簡單使用AffineTransform改變方式,圖形繪製...

Rotated

import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.FontMetrics; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.geom.AffineTransform; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class AngleText { 

    public static void main(String[] args) { 
     new AngleText(); 
    } 

    public AngleText() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     public TestPane() { 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(200, 200); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      String text = "I don't see the problem"; 
      FontMetrics fm = g2d.getFontMetrics(); 
      int x = (getWidth() - fm.stringWidth(text))/2; 
      int y = ((getHeight() - fm.getHeight())/2) + fm.getDescent(); 
      g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(45), getWidth()/2, getHeight()/2)); 
      g2d.drawString(text, x, y); 
      g2d.dispose(); 
     } 

    } 

} 

欲瞭解更多詳情,您可以在Transforming Shapes, Text, and Images

+0

感謝看一看!它現在很好用! –

+0

@MadProgrammer,當我運行你的代碼時,字符串不會以相同的方式出現。截圖在https://www.dropbox.com/s/7chtk4sb1oz4cmy/string%20rotation.png – wannik