2013-01-16 54 views
1
Graphics g = image.getGraphics(); 
    FontMetrics fm = g.getFontMetrics(); 
     int actual_width= fm.stringWidth("My Value"); 
    drawString("My Value",total_width-actual_width,ypos); 
    g.dispose(); 
    ImageIO.write(image, "bmp", new File(c:\\output.bmp)); 

如何使此右對齊右對齊圖像上的文字

實際輸出

enter image description here

所需的輸出

enter image description here

輸出: -

System.out.println("total_width=" + image.getWidth() + " actual_width=" + actual_width); 

    total_width=352 actual_width=46 
    total_width=352 actual_width=38 
    total_width=352 actual_width=68 
    total_width=352 actual_width=73 
    total_width=352 actual_width=36 
+2

爲了更好地幫助越早,張貼[SSCCE(http://sscce.org/)。 –

回答

4

這裏是一個小SSCCE演示一個解決問題的方法:

import javax.swing.*; 
import java.awt.*; 
import java.awt.image.*; 

public class Test extends JFrame{ 

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

    private Test(){ 
     final BufferedImage img = new BufferedImage(300, 300, BufferedImage.TYPE_INT_ARGB); 
     Graphics g = img.createGraphics(); 
     g.setColor(Color.BLACK); 

     int total_width = img.getWidth(); 
     int y = 30; 
     int padding = 100; 

     String [] words = new String[]{"Example", "Of", "Right", "Alignment"}; 
     for(int i = 0; i < words.length; i++){ 
      int actual_width = g.getFontMetrics().stringWidth(words[i]); 
      int x = total_width - actual_width - padding; 
      g.drawString(words[i], x, y += 30); 
     } 
     g.dispose(); 


     setContentPane(new JPanel(){ 
      public void paintComponent(Graphics g){ 
       super.paintComponent(g); 
       g.drawImage(img, 0, 0, null); 
      } 
     }); 

     setSize(300,300); 
     setResizable(false); 
     setLocationRelativeTo(null); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setVisible(true); 
    } 
} 
+0

文字居中對齊,不對齊。 –

+0

如果'image.getWidth() - (2 * padding)== stringWidth',它將被居中。爲了更好..好吧,看看上面。 –

+0

右對齊是否是組件的寬度減去文本寬度是否有意義?這是小學數學。 – rtheunissen