2009-11-20 82 views
1

我有一個圖像。在圖像的底部,我想創建一個高度爲100的彩色條。我已經完成了創建條的工作,並且我基本上可以在該部分中編寫字符串(例如,圖像的版權等)。以下是我的方法。Java Graphics Font - 如何確保角色位於特定區域?

public static BufferedImage captionMyImage(BufferedImage sourceImage) { 

    int height=sourceImage.getHeight(); 
    int width=sourceImage.getWidth(); 

    System.out.println("Image Height: "+height); 
    System.out.println("Image Width: "+width); 

    int min=20; //fifty pixels 
    int newHeight=(int) (0.1*height>min ? 1.1*height : height+min); 
    int difference=newHeight-height; 
    System.out.println("new height:"+newHeight); 
    System.out.println("Difference:"+difference); 
    BufferedImage bgImage=new BufferedImage(width,newHeight,BufferedImage.TYPE_INT_RGB); 



    /**Create a Graphics from the background image**/ 
    Graphics2D g = bgImage.createGraphics(); 

    //g.drawRect(0, 0, width, ((int)0.1*height>min) ? (int)1.1*height : height+min); 
    g.setColor(Color.RED); 
    g.fillRect(0, 0, bgImage.getWidth(), bgImage.getHeight()); 
    g.setColor(Color.YELLOW); 



    /**Set Antialias Rendering**/ 
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
      RenderingHints.VALUE_ANTIALIAS_ON); 
    /** 
    * Draw background image at location (0,0) 
    * You can change the (x,y) value as required 
    */ 
    g.drawImage(sourceImage, 0, 0, null); 

    int strX=sourceImage.getWidth()/2; 
    int strY=sourceImage.getHeight()+difference/2; 
    System.out.println("X: "+strX); 
    System.out.println("Y: "+strY); 
    g.setFont(new Font(g.getFont().getName(),Font.PLAIN,20)); 
    g.drawString("(c)www.sanjaal.com",strX ,strY); 

    g.dispose(); 

    return bgImage; 
} 

我知道我計算x和y爲drawString之()方法僅僅是一個簡單的,並具有文本變爲邊界之外有時問題的值的方式(取決於圖像大小和文本的長度)

我想確保我定義的底部條上圖像中的文本始終與圖像的右側部分(邊界)對齊,但不會超出邊界。我怎樣才能做到這一點?記住文本長度可以是動態的。

請問java圖形專家在那裏分享你的想法如何實現?

回答

4
String msg = "(c)www.sanjaal.com"; 
int margin = 2; 
g.drawString(msg, getWidth() - g.getFontMetrics().stringWidth(msg) - margin, strY); 
+0

謝謝您的快速回復。這正是我正在尋找的。 – 2009-11-20 20:53:26