Drawing Text In Java

C

Chase Preuninger

BufferedImage img = new BufferedImage(50 * text.length(), 100,
BufferedImage.TYPE_3BYTE_BGR);

Graphics2D g = img.createGraphics();
FontMetrics fm = g.getFontMetrics(f);

g.setBackground(Color.WHITE);
g.clearRect(0, 0, img.getWidth(), img.getHeight());

g.setFont(f);
g.setColor(Color.BLACK);
g.drawString(text, 50, fm.getAscent() + 10);

How can I tell how big to make my image based on the font and text?
 
J

John B. Matthews

Chase Preuninger said:
BufferedImage img = new BufferedImage(50 * text.length(), 100,
BufferedImage.TYPE_3BYTE_BGR);

Graphics2D g = img.createGraphics();
FontMetrics fm = g.getFontMetrics(f);

g.setBackground(Color.WHITE);
g.clearRect(0, 0, img.getWidth(), img.getHeight());

g.setFont(f);
g.setColor(Color.BLACK);
g.drawString(text, 50, fm.getAscent() + 10);

How can I tell how big to make my image based on the font and text?

The API pretty much covers it at the pixel level:

<http://www.j2ee.me/javase/6/docs/api/java/awt/FontMetrics.html>

Alternatively, TextLayout offers a convenient abstraction:

<http://java.sun.com/javase/6/docs/api/java/awt/font/TextLayout.html>

Perhaps you can explain more about your goal and provide a short example
of where you're having trouble: <http://pscode.org/sscce.html>
 
R

Roedy Green

How can I tell how big to make my image based on the font and text?

That is an artistic decision. You can use FontMetrics to get some idea
how my some given String really is.

see http://mindprod.com/jgloss/fontmetrics.html

--
Roedy Green Canadian Mind Products
http://mindprod.com

"If people become accustomed to lying, they will unconsciously commit every possible wrong deed. Before they can act wickedly, they must lie, and once they begin to lie they will act wickedly without concern."
~ Gautama Buddha
 
C

Chase Preuninger

But gow can I create a FontMetrics if I don't have a graphics until
after I create the image and therefore can't get the fontrendercontext?
 
A

Andrew Thompson

But gow can I create a FontMetrics if I don't have a graphics until
after I create the image and therefore can't get the fontrendercontext?

You might try hiring someone with the faintest clue.
(Just a thought.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,277
Latest member
VytoKetoReview

Latest Threads

Top