03 Adding a Background Shape
Step 4/11 — 04 Preferred Label Size
01 Rendering the Label Text 02 Using Text Utilities 03 Adding a Background Shape 04 Preferred Label Size 05 Render Performance 06 Text Alignment 07 Line Wrapping 08 Data From Tag 09 Hit-Testing 10 Visibility 11 Bounds
05 Render Performance

# Preferred Label Size

LabelStyleBase provides the abstract method getPreferredSize that needs to be implemented to tell the framework how large the label prefers to be.

Until now, the label style implementation has returned a fixed preferred size. This means that the label size is not adjusted to shorter or longer texts. Also, the label wouldn’t grow in height if the text contains a line break.

We adjust the implementation of getPreferredSize to measure the label text and return the measured size. TextRenderSupport.measureText helps us to get the desired size. We add a small padding of 3 for each side.

    protected getPreferredSize(label: ILabel): Size {
      // measure the label text using the font
      const { width, height } = TextRenderSupport.measureText(label.text, font)
      // return the measured size plus a small padding
      return new Size(width + padding + padding, height + padding + padding)
    }

To see the labels adjust to different text lengths, select a node or edge and press F2 to edit the label. Press Ctrl+Return to insert a line break.

We also adjust the translate transform of the text element in `createVisual` to consider the padding vertically.

    textElement.setAttribute('transform', `translate(${padding} ${padding})`)

Note | The ILabelModel may or may not take the preferred size into account. Therefore, it is not guaranteed that the label will become as large as the preferred size. Most label models, like ExteriorLabelModel, InteriorLabelModel, FreeLabelModel etc. will respect the value, though. Usually, only stretch label models like InteriorStretchLabelModel, that fit the content into the owner node, will result in a different size.

05 Render Performance