Search code examples
xamarinxamarin.formsskiaskiasharp

How to measure trailing spaces using SkiaSharp?


SkiaSharp doesn't consider the white spaces, when a text contains white spaces in prefix or suffix. It returns the text width only and ignore the white spaces. I am using the following code snippet to measure a string.

        SKPaint paint = new SKPaint();
        paint.Typeface = SKTypeface.FromFamilyName("Calibri");
        paint.TextSize = 15;

        SKRect rect = new SKRect();
        paint.MeasureText(" Test ", ref rect);

Is there any option to measure a text with trailing spaces using SkiaSharp?


Solution

  • You need to use the return value of MeasureText:

    float width = paint.MeasureText(" Test ", ref rect);
    float whiteSpaceWidth = width - rect.Width;
    

    And if you want to adjust rect to include the whitespace also:

    rect.Left -= whiteSpaceWidth / 2;
    rect.Right += whiteSpaceWidth / 2;