Vasu
Vasu

Reputation: 22422

java Graphics2D - generate dynamic image

I am learning Java Graphics2D and I have got an issue with generating the image.

Please find the below code and the output image:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class DynamicImage {

    public static void main(String[] args) {

            Dimension imgDim = new Dimension(1000,1000);
            BufferedImage buffImage = new BufferedImage(imgDim.width, imgDim.height, BufferedImage.TYPE_INT_RGB);

            Graphics2D g2d = buffImage.createGraphics();
            g2d.setBackground(Color.WHITE);
            g2d.fillRect(0, 0, imgDim.width, imgDim.height);
            g2d.setColor(Color.BLACK);
            BasicStroke bs = new BasicStroke(2);
            g2d.setStroke(bs);

            Font font = new Font("Arial", Font.PLAIN, 20);
            g2d.setFont(font);

            String[] alphabets = {"A","B","C","D","E","F","G","H","I","J","K"};

            for(int i=0;i<alphabets.length;i++) {
                g2d.drawString(alphabets[i], (50*(i)), 500);
                g2d.drawLine((50*(i)), 500, (50*(i+1)), 500);
            }
        try {
            ImageIO.write(buffImage, "png", new File("C:\\Alphabets.png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

enter image description here

As you could notice above, Alphabets are overlapping with the line, which I don't want, In other words, I want my output as below: A____B___C___D___E___F___G___H___I___J___K___

Could you please help by correcting the above code to get the required output ?

Upvotes: 0

Views: 921

Answers (1)

camickr
camickr

Reputation: 324118

You will need to use the FontMetrics class:

FontMetrics fm = g2d.getFontMetrics();

Then you will need to get the width of each character:

int width = fm.stringWidth( alphabets[i] );

Then start drawing the line after the character width:

g2d.drawLine((50*(i)) + width, 500, (50*(i+1)), 500);

Above logic is not tested, but I hope you get the idea.

Upvotes: 2

Related Questions