How to left,center and right align text written on BufferedImage

If you want to write a text on a BufferedImage and want it to be right aligned, you can try this code . It basically uses Fontmetrics class to calculate the width of the given text for a given font and accordingly adjusts X and Y axis of the text to be written

package images;
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
 
public class TextAlignment extends JFrame{
 
    public static void main(String [] args){
        new TextAlignment();
    }
 
    private TextAlignment(){
        final BufferedImage img = new BufferedImage(300, 300, BufferedImage.TYPE_INT_ARGB);
        Graphics g = img.createGraphics();
        g.setColor(Color.BLACK);
 
        int total_width = img.getWidth();
        int y = 30;
        int padding = 100;
 
        String [] words = new String[]{"Example", "Of", "Right", "Alignment"};
        for(int i = 0; i < words.length; i++){
            int actual_width = g.getFontMetrics().stringWidth(words[i]);
            int x = total_width - actual_width - padding;
            g.drawString(words[i], x, y += 30);
        }
        g.dispose();
 
 
        setContentPane(new JPanel(){
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(img, 0, 0, null);
            }
        });
 
        setSize(300,300);
        setResizable(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

Output would be :

For center aligned try this code:

  String [] words = new String[]{"Example", "Of", "Right", "Alignment"};
        for(int i = 0; i < words.length; i++){
            int actual_width = g.getFontMetrics().stringWidth(words[i]);
            int x = (total_width - actual_width)/2;
            g.drawString(words[i], x, y += 30);
        }
        g.dispose();

Output would be like this :

 

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *