documentationfor yFiles for HTML 2.6

The Preferred Label Size

As already described in the section Labels, the preferred size of a label is a weak suggestion of what size the label should have, given no context.

Setting the preferred size for a label directly (via setLabelPreferredSize) is a rare use-case. You should rather implement the getPreferredSize interface method on the renderer accordingly, since it should be up to the visualization to determine the space needed to display the label.

The final layout (position, size, and rotation) of a label is determined by ILabelModels and their ILabelModelParameters, which usually take the suggested preferred size of the renderer into consideration. For example, the ILabelModelParameter might specify the label as “centered in the node.” To calculate the exact location of the label, the ILabelModel needs to know the exact width and height of the label’s visualization which is determined by the renderer.

Because of this, the ILabelStyleRenderer interface requires an implementation of the getPreferredSize method. If you implement a custom label visualization, make sure that this method returns a good approximation of the final visualization.

Typical properties to take into consideration are:

  1. The label’s text
  2. Font and font size
  3. Character and line spacing
  4. Rendering settings
  5. Visual features, e.g. an added icon

The predefined label visualizations in yFiles for HTML (for example, DefaultLabelStyleRenderer) have an efficient implementation for measuring the label size considering the first 4 points.

Since in most cases you probably want to add visual features to the bare text, you can simply wrap the existing implementation of getPreferredSize and add an estimation for the space needed by your visualization and you are done.

An example for this is the IconLabelStyle which decorates the label text with an icon. The IconLabelStyleRenderer includes the icon for the size measurements:

Example getPreferredSize decorator which measures the size of a text decorated with an icon
/**
 * @param {!ILabel} label
 * @param {!ILabelStyle} labelStyle
 * @returns {!Size}
 */
getPreferredSize(label, labelStyle) {
  // measure the text
  const textSize = this.measureMyText(label.text)
  const iconSize = this.getIconSize()
  // add the icon size for an icon placed at the side of the text:
  // add the width and use the max of the text and icon height
  return new Size(textSize.width + iconSize.width, Math.max(textSize.height, iconSize.height))
}

getPreferredSize(label: ILabel, labelStyle: ILabelStyle): Size {
  // measure the text
  const textSize = this.measureMyText(label.text)
  const iconSize = this.getIconSize()
  // add the icon size for an icon placed at the side of the text:
  // add the width and use the max of the text and icon height
  return new Size(textSize.width + iconSize.width, Math.max(textSize.height, iconSize.height))
}