0

Can someone check my syntax here? I am passing "Times New Roman","Arial","Verdana" to fontName and using 8,12,15 etc. for fontSize. It never changes the font here. I am doing this to write some text over an image.

Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
g2d.drawImage(photo, 0, 0, null);
g2d.setColor(Color.white);
Font font = new Font(fontName, Font.PLAIN, fontSize);
g2d.setFont(font);
g2d.drawString(text,x,y);

2 Answers 2

2

I finally found out that none of fonts from my list were there on the system so I had to use getAllFonts() method and pass only those fonts from the list .

0

You should be doing this

BufferedImage img = new BufferedImage(
    w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.drawImage(photo, 0, 0, null);
g2d.setPaint(Color.red);
//example :     g2d.setFont(new Font("Serif", Font.BOLD, 15));
g2d.setFont(new Font(fontName, Font.BOLD, size));
String s = "Hello, world!";
// assuming x & y is set using graphic's font metrics
g2d.drawString(s, x, y);
g2d.dispose();

Excerpt from sun documentation

getGraphics

public Graphics getGraphics() This method returns a Graphics2D, but is here for backwards compatibility. createGraphics is more convenient, since it is declared to return a Graphics2D.

This does not really mean that you should not use getGraphics API. Just that the above code worked for me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.