Java Tip: Drawing a TextLayout ============================== Vijay Kumar `TextLayout` objects among other things can be used to draw styled character data. The `draw()` method of the object can be used to draw the rendered text to a `Graphics2D` object. But the `x` and `y` co-ordinates passed to `draw()` is not the position of the top left corner as would be expected. The `x` and `y` coordinate is the position of the origin. The origin of a `TextLayout` is the intersection of the objects baseline with its left edge. The baseline is the horizontal line on which characters of a font are positioned. Figure (a) shows the locations of the baseline and the origin. .BaseLine, origin and bounds image::text-layout.png[] Given the position of the top left corner to draw the `TextLayout`, the position of the origin has to be calculated. The `getBounds()` method of `TextLayout` can be used for this purpose. The `getBounds()` method returns the bounding rectangle of the rendered `TextLayout` object. The top left corner of the returned bounding rectangle is relative to the origin of the `TextLayout` as shown in figure b. The position of the origin can be calculated as shown in the following piece of code. ------ TextLayout layout; Graphics2D g2; Rectangle2D bounds; float x, y; /* Position of top left corner to draw the TextLayout. */ float ox, oy; /* Position of origin to draw the TextLayout. */ ... ... bounds = layout.getBounds(); ox = x - bounds.getX(); oy = y - bounds.getY(); layout(g2, ox, oy); ------ The text can be centered in a rectangle `(px, py, pw, ph)` using the following piece of code. ------ TextLayout layout; Graphics2D g2; Rectangle2D bounds; float px, py, pw, ph; float cx, cy; /* Center X, Y */ float ox, oy; /* Origin X, Y */ ... ... bounds = layout.getBounds(); cx = px + pw / 2 - bounds.getWidth() / 2; cy = py + ph / 2 - bounds.getHeight() / 2; ox = cx - bounds.getX(); oy = cy - bounds.getY(); layout(g2, ox, oy); ------