1

画像があります。画像の下部に、たとえば高さ 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 の専門家は、これをどのように実現できるかについてあなたのアイデアを共有してくれますか?

4

1 に答える 1

4
String msg = "(c)www.sanjaal.com";
int margin = 2;
g.drawString(msg, getWidth() - g.getFontMetrics().stringWidth(msg) - margin, strY);
于 2009-11-20T20:49:38.207 に答える