The Preferred Label Size
As described in the section Labels, the preferred size of a label is a suggestion for the ideal size of the label, assuming no other constraints.
Setting the preferred size for a label directly (via setLabelPreferredSize) is rarely necessary. Instead, you should implement the getPreferredSize interface method in your renderer. The visualization logic should 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 consider the renderer’s suggested preferred size. For example, a ILabelModelParameter might specify that the label should be “centered in the node.” To calculate the label’s exact location, the ILabelModel needs to know the exact width and height of the label’s visual representation, as determined by the renderer.
Because of this, the ILabelStyleRenderer interface requires an implementation of the getPreferredSize method. If you implement a custom label visualization, ensure that this method returns a reasonable approximation of the final visualization’s size.
Consider these properties when determining the preferred size:
- The label’s text
- Font and font size
- Character and line spacing
- Rendering settings
- Visual features, such as an added icon
The predefined label visualizations in yFiles for HTML (for example, the renderer or LabelStyle) efficiently measure the label size, considering the first four points.
Since you’ll often want to add visual features to the bare text, you can wrap the existing implementation of getPreferredSize and add an estimation for the space needed by your visualization.
For example, the IconLabelStyle decorates the label text with an icon. Its renderer includes the icon when measuring the 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)
)
}