New to Telerik Document Processing? Download free 30-day trial

Create Custom Text Measurer in .NET Standard

Product Version Product Author
2021.1.212 RadSpreadProcessing Martin Velikov

Description

Due to .NET Standard APIs limitations, the SimpleTextMeasurer provides basic functionality for text measuring and it is not expected to be an all-purpose measurer. So in order to measure the specific text in a more precise way, you will need to create a custom implementation of a text measure and set it to the TextMeasurer property of the SpreadExtensibilityManager.

Solution

In the example below, we are demonstrating how to create a custom TextMeasurer inheriting the SpreadTextMeasurerBase abstract class and set it to the TextMeasurer property of the SpreadExtensibilityManager.

Creating a CustomTextMeasurer

public class CustomTextMeasurer : SpreadTextMeasurerBase 
{ 
    private static readonly double ratioX = 1.035; 
    private static readonly double ratioY = 1; 
    private static readonly double ratioBaseline = 1; 
 
    private readonly SpreadTextMeasurerBase originalMeasurer; 
 
    public CustomTextMeasurer(SpreadTextMeasurerBase originalMeasurer) 
    { 
        this.originalMeasurer = originalMeasurer; 
    } 
 
    public override TextMeasurementInfo MeasureText(TextProperties textProperties, FontProperties fontProperties) 
    { 
        TextMeasurementInfo info = originalMeasurer.MeasureText(textProperties, fontProperties); 
 
        Size size = info.Size; 
        return new TextMeasurementInfo() 
        { 
            BaselineOffset = info.BaselineOffset * ratioBaseline, 
            Size = new Size( 
                size.Width * ratioX, 
                size.Height * ratioY), 
        }; 
    } 
 
    public override TextMeasurementInfo MeasureTextWithWrapping(TextProperties textProperties, FontProperties fontProperties, double wrappingWidth) 
    { 
        TextMeasurementInfo info = originalMeasurer.MeasureText(textProperties, fontProperties); 
 
        Size size = info.Size; 
        return new TextMeasurementInfo() 
        { 
            BaselineOffset = info.BaselineOffset * ratioBaseline, 
            Size = new Size( 
                size.Width * ratioX, 
                size.Height * ratioY), 
        }; 
    } 
} 
The following example shows how to set the custom implementation inheriting the SpreadTextMeasurerBase abstract class to the TextMeasurer property of the SpreadExtensibilityManager.

Setting the CustomTextMeasurer

SpreadTextMeasurerBase customTextMeasurer = new CustomTextMeasurer(SpreadExtensibilityManager.TextMeasurer);  
SpreadExtensibilityManager.TextMeasurer = customTextMeasurer;  
In this article