[OpenJDK 2D-Dev] Missing floating-point-precision method in font measuring API

Dmitry Batrak dmitry.batrak at jetbrains.com
Tue Dec 20 10:11:06 UTC 2016

Missing floating-point-precision method in font measuring API


It looks like there's currently a gap in text measuring API with respect to
methods working with floating point coordinates. It's not something new, but
with HiDPI support added in Java 9, it seems to become more significant.

Consider the following simplified use case of custom text component which
supports highlighting. Suppose we initially draw a couple of characters
(in paintComponent method) like this

  char[] text = new char[] {'a', 'b'};
  int x = ..., y = ...;
  g.drawChars(text, 0, 2, x, y);

But then we need draw the second character in a different color, and we'd
the glyph positions to be the same. We assume the text is simple (e.g.
without ligatures, etc). The simplest way to do it is

  g.drawChars(text, 0, 1, x, y);
  int advance = g.getFontMetrics().charWidth(text[0]);
  g.drawChars(text, 1, 1, x + advance, y);

This will not work though, if advance is not integer. We wouldn't be
by this issue, if we didn't use fractional metrics, but in HiDPI case
the advance can fractional even if fractional metrics are not used -
glyph is positioned at integer coordinates in device space, so e.g. with
200% scale, in user space it can contain half-pixels. Current solution is

 float advance = (float)g.getFontMetrics().getStringBounds(text, 0, 1, g).x;
 g.drawString(new String(text, 1, 1), x + advance, (float)y);

Alternatively, we can use font.createGlyphVector() instead of
(this is done internally anyway), but in any case an instance of GlyphVector
will be created in the process, which seems unnecessary - all we need is
which is already available, we just cannot get it directly without it being
rounded. Creation of new String instance, copying underlying text, also
seem to be necessary, but there's no other method to draw part of existing
using floating point coordinates.

Do you think adding corresponding new floating-point-based method to
(and maybe to Graphics2D) makes sense? Maybe it's planned already as part of
HiDPI-related activity? Should I raise an RFE via bugs.java.com for this?

Dmitry Batrak
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/2d-dev/attachments/20161220/3347c349/attachment.html>

More information about the 2d-dev mailing list