Why Node Labels Exceed the Width of Their Nodes
Questions & AnswersSummary
Description
The yFiles library uses Java's font rendering mechanism to scale the text of node labels according to the current zoom level of the view.
This rendering mechanism, however, yields non-linear results regarding the width of text, since both text spacing and glyphs can be different at subsequent zoom levels.
As a consequence, it is possible that node labels exceed the width of their nodes when the zoom level changes (both increases or decreases).
Possible Solutions
A possible workaround that better keeps the label text inside its node, relies on using fractional metrics for the rendering. Fractional metrics is supported by Java by means of a rendering hint set on the Graphics2D context. The following code snippet shows how the rendering hint can be set using a customized DefaultGraph2DRenderer for a given view.
// 'view' is of type y.view.Graph2DView.
view.setGraph2DRenderer(new DefaultGraph2DRenderer() {
protected void paint(Graphics2D gfx, NodeRealizer nr) {
gfx.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
super.paint(gfx, nr);
}
});
As of yFiles version 2.6.1, using fractional metrics for rendering can be conveniently specified by means of the setRenderingHints method as presented in the following code snippet, for example.
// 'view' is of type y.view.Graph2DView.
RenderingHints rh = view.getRenderingHints();
rh.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
view.setRenderingHints(rh);
YLabel.setFractionMetricsForSizeCalculationEnabled(true);
Note that for consistent label rendering results, it is strongly recommended to also call the YLabel.setFractionMetricsForSizeCalculationEnabled class method appropriately.