Search code examples
javajava-2d

how can I get Font X offset width in java2D?


I need print two words: "A" and "B" using java 2D

font size = 100;

"A" font family: Bodoni MT Poster Compressed

"B" font family: Arial

I writed below codes to do it:

BufferedImage image = new BufferedImage(400, 300, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
{//fill bg color
    g.setColor(new Color(255,255,255));
    g.fillRect(0, 0, image.getWidth(), image.getHeight());
}           

int FONT_SIZE=100;//set font size
{//print A
    g.setColor(new Color(0,0,0));
    g.setFont(new Font("Bodoni MT Poster Compressed", Font.PLAIN ,FONT_SIZE));      
    g.drawString("A",0,FONT_SIZE);
}
{//print B
    g.setColor(new Color(0,0,0));
    g.setFont(new Font("Arial", Font.PLAIN ,FONT_SIZE));        
    g.drawString("B",FONT_SIZE,FONT_SIZE);
}
g.dispose();

I get the result image: enter image description here

but I need like this (make by PhotoShop):enter image description here

I think the question at g.drawString("B",FONT_SIZE,FONT_SIZE);

How can I get the font X offset width?

thanks for help :)


Solution

  • After you do the setFont, declare a variable like

    FontMetrics fm = g.getFontMetrics();
    int strA = fm.stringWidth("A"),
        strB = fm.stringWidth("B"),
        strH = fm.getHeight();
    

    Now that you have all the dimensions of the letters, set their positions (px is distance from the left edge to the letter, py from the top to the baseline of the font)

    int px = ..., py = ...
    g.drawString ("A", px, py);
    

    And similarly for "B". Hope that helps, - M.S.