Get string size in Java (no graphics object available)
•
Java
I'm trying to write an application that needs to draw many strings using the graphics2d class in Java I need to get the size of each string object (to calculate the exact location of each string)
When I try to create my own object:
FontRenderContext frc = new FontRenderContext(MyFont.getTransform(),true,true)
Then I get the string boundary. I always get different sizes when I use graphics2d in the paint () method When getfontrendercontext() method gets fontrendercontext The difference is small (about 1e-3), but I don't know why there is any difference?
But is there a better and safer way to get the size of a string?
Thnx any help in advance!
Solution
Try to have a class with fontmetrics; The stringwidth method returns the size of a string
JComponent c = getSomeKindOfJComponent(); FontMetrics fm = c.getFontMetrics(c.getFont()); // or another font int strw = fm.stringWidth("My text");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码