Skiasharp: How to measure trailing spaces using SkiaSharp?

Created on 6 Aug 2018  路  2Comments  路  Source: mono/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?

Most helpful comment

I think this is a "feature" of the native skia, so we can't really do anything about it:
https://fiddle.skia.org/c/51eda9db1e0301a62118213718767e4c

But, we can because we are software developers! If you really need to measure the space, maybe wrap the text with some character, say the period ., and then just subtract 2x:

var text = "  SkiaSharp  ";
var wrapper = ".";

var wrapperWidth = paint.MeasureText(wrapper);
var textWidth = paint.MeasureText(wrapper + text + wrapper);

var textWidth = textWidth - (wrapperWidth + wrapperWidth);

All 2 comments

I think this is a "feature" of the native skia, so we can't really do anything about it:
https://fiddle.skia.org/c/51eda9db1e0301a62118213718767e4c

But, we can because we are software developers! If you really need to measure the space, maybe wrap the text with some character, say the period ., and then just subtract 2x:

var text = "  SkiaSharp  ";
var wrapper = ".";

var wrapperWidth = paint.MeasureText(wrapper);
var textWidth = paint.MeasureText(wrapper + text + wrapper);

var textWidth = textWidth - (wrapperWidth + wrapperWidth);

@mattleibow Thanks for your answer. Previously, I have used SKRect value which is not included the white spaces. After that, I have checked the returned float value from SKPaint.MeasureText(" Test ", ref rect) which returns proper width value including while spaces.

Was this page helpful?
0 / 5 - 0 ratings