chevron_right Demos chevron_right Tutorial: Label Style Implementation chevron_right 07 Line Wrapping
06 Text Alignment
08 Data From Tag

Line wrapping

So far, the label text was placed in a single line unless it contained manual line breaks. In this step, we’ll introduce automatic line wrapping to our label style. Since SVG <text> does not support line wrapping out-of-the-box, TextRenderSupport provides functionality for this purpose. The enum TextWrapping can be used to specify different wrapping policies like wrapping at character, or at word boundaries.

First, we define parameters for the line wrapping policy and the maximum size in the style’s constructor.

constructor(
  wrapping: TextWrapping = TextWrapping.NONE,
  maxSize: Size = Size.INFINITE
) {
  super()
  this.wrapping = wrapping
  this.maxSize = maxSize
}

Now, we can use these values in our rendering code. But first, we will adjust the preferred size calculation to respect the maximum size.

// subtract the padding from the maximum size for text measuring
const maxTextSize = new Size(
  this.maxSize.width - padding - padding,
  this.maxSize.height - padding - padding
)
// measure the label text using the maximum size and the wrapping
const { width, height } = TextRenderSupport.measureText(
  label.text,
  font,
  maxTextSize,
  this.wrapping
)
// add the padding to the measured text size again
return new Size(width + padding + padding, height + padding + padding)

Finally, we can use the maximum size and line wrapping policy in TextRenderSupport.addText.

// subtract the padding from the maximum size for text measuring
const maxTextSize = new Size(
  this.maxSize.width - padding - padding,
  this.maxSize.height - padding - padding
)
const textContent = TextRenderSupport.addText(
  textElement,
  text,
  font,
  maxTextSize,
  this.wrapping
)

In the sample graph, you can see the different options for line wrapping. Edit the labels using F2 to see how the wrapping behaves.