Java图形字体-如何确保字符位于特定区域?

Java图形字体-如何确保字符位于特定区域?,java,graphics,image-manipulation,graphics2d,Java,Graphics,Image Manipulation,Graphics2d,我有一个形象。在图像的底部,我想创建一个彩色条,比如说,高度100。我已经完成了创建该条,我基本上可以在该部分写入字符串(例如,图像版权等)。以下是我的方法 public static BufferedImage captionMyImage(BufferedImage sourceImage) { int height=sourceImage.getHeight(); int width=sourceImage.getWidth(); System.out.prin

我有一个形象。在图像的底部,我想创建一个彩色条,比如说,高度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图形专家是否可以分享您关于如何实现这一点的想法?

谢谢您的快速回复。这正是我想要的。谢谢你的快速回复。这正是我要找的。
String msg = "(c)www.sanjaal.com";
int margin = 2;
g.drawString(msg, getWidth() - g.getFontMetrics().stringWidth(msg) - margin, strY);