Java: How to draw strring () from a line

I am displaying some graphic text on the screen using the drawString (...) function of the Java2D library.

Referring to the figure in this article, I want my string to be taken from an Ascender string, not BaseLine. In simple words, is there a way to calculate the height b / w of the approach line and baseline?

+4
source share
3 answers

You can get the FontMetrics object of the font used and determine the ascent using getAscent() or getMaxAscent() , depending on what is appropriate for your case.

+2
source

A normal drawString aligns the baseline with a y argument. If you want to draw a line so that the elevation line matches y , you need to pass y + fm.getAscent() , where fm is the current FontMetrics object. See the example below.

This screenshot:

enter image description here

generated by the following code:

 FontMetrics fm = g.getFontMetrics(); g.setColor(Color.RED); g.drawLine(10, 10, 100, 10); g.setColor(Color.BLACK); g.drawString("Hello frog", 10, 10 + fm.getAscent()); 
+5
source

Add FontMetrics.getAscent() to the y position before rendering.

+1
source

Source: https://habr.com/ru/post/1380181/


All Articles