簡體   English   中英

Java Graphics字體 - 如何確保字符位於特定區域?

[英]Java Graphics Font - How to make sure the characters lie in particular area?

我有一個圖像。 在圖像的底部,我想創建一個高度為100的彩色條帶。我已經完成了創建條帶,我基本上可以在該部分編寫字符串(例如圖像的版權等)。 以下是我的方法。

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;
}

我知道我為drawString()方法計算x和y的值的方法只是一個簡單的方法,並且有時文本超出邊界的問題(取決於圖像大小和文本長度)

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

那里的java Graphics專家會分享你如何實現這一點的想法嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM