Painting Labels Atop Other Graph Elements |
| Applies to: yFiles 2.4, yFiles 2.3, yFiles 2.2, yFiles 2.1, yFiles 2.0 |
Type: Tips & Tricks
Categories this article belongs to:
| yFiles for Java | > yFiles Viewer | > Displaying and Editing Graphs | > Realizer-Related Features |
Changing a view's rendering order so that labels are painted atop of all other graph elements.
By default, the rendering of graph elements is performed by the Graph2DRenderer
instance registered with a Graph2DView
.
To have the labels painted atop of all other graph elements, the rendering order has to be changed so that the labels are painted last, i.e., after all the graph's nodes and edges.
This can be achieved by registering a customized Graph2DRenderer instance with the Graph2DView using its Graph2DView.setGraph2DRenderer(y.view.Graph2DRenderer)
method.
The following sample code presents a custom Graph2DRenderer implementation that paints labels last. To do so, it performs two rendering passes:
- It paints all nodes and edges. Their labels get explicitly marked as invisible so that they are not painted.
- It marks the node labels and edge labels visible again, and then paints only these.
package demo.view; import java.awt.Graphics2D; import y.view.DefaultGraph2DRenderer; import y.view.EdgeRealizer; import y.view.Graph2D; import y.view.NodeRealizer; public class LabelsLastGraph2DRenderer extends DefaultGraph2DRenderer { boolean firstPass; /** * Renders the given Graph2D on the given Graphics2D context. * Rendering is performed by calling the paint() method of each * NodeRealizer and EdgeRealizer associated with the nodes and edges * of the graph. */ public void paint(final Graphics2D gfx, final Graph2D graph) { firstPass = true; super.paint(gfx, graph); firstPass = false; super.paint(gfx, graph); } /** * Paint nodes without labels in the first pass, and * then only their labels in the second pass. */ protected void paint(Graphics2D gfx, NodeRealizer nr) { if (firstPass) { // Mark labels as invisible. for (int i = 0; i < nr.labelCount(); i++) nr.getLabel(i).setVisible(false); super.paint(gfx, nr); // Mark labels as visible. for (int i = 0; i < nr.labelCount(); i++) nr.getLabel(i).setVisible(true); } else { for (int i = 0; i < nr.labelCount(); i++) nr.getLabel(i).paint(gfx); } } /** * Paint edges without labels in the first pass, and * then only their labels in the second pass. */ protected void paint(Graphics2D gfx, EdgeRealizer er) { if (firstPass) { // Mark labels as invisible. for (int i = 0; i < er.labelCount(); i++) er.getLabel(i).setVisible(false); super.paint(gfx, er); // Mark labels as visible. for (int i = 0; i < er.labelCount(); i++) er.getLabel(i).setVisible(true); } else { for (int i = 0; i < er.labelCount(); i++) er.getLabel(i).paint(gfx); } } } |
| Keywords: | labels - rendering - Graph2DRenderer - on top - atop - label - node - edge - paint - drawing - sequence |


