Forum Libraries, Components, and Plugins

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Why Skiasharp.MeasureText gives different results?

Hello Everibody,

can sombody help me?

I use the MeasureText function with the same text, but I get diferent values? What could be the reason?
First result: 281, second result 283.
Here is the code:

using (var paint = new SKPaint()
{
TextSize = 38.0f,
IsAntialias = true,
Color = SKColors.DarkGray,
TextAlign = SKTextAlign.Left
})
{
string test = "this is a test text";

SKRect bounds = new SKRect();
paint.MeasureText(test, ref bounds);
Console.WriteLine(bounds.Width);

float w = paint.MeasureText(test);
Console.WriteLine(w);

}

Thank you!

Answers

  • YelinzhYelinzh Member, Xamarin Team Xamurai

    I've reproduced the code and it works as you said. The different result is because the two return values are of different types.
    1.SKPaint.MeasureText(String) returns the width of the text.

    ...
    float w = paint.MeasureText(test);
    Console.WriteLine(w);
    

    2.'bounds' is the bounds of the text relative to (0, 0). SKRect.Width is the width of the rectangle.

    ...
    SKRect bounds = new SKRect()
    paint.MeasureText(test, ref bounds);
    Console.WriteLine(bounds.Width);
    

    Change the code as below and you'll get the same result.

    string test = "this is a test text";
    
    SKRect bounds = new SKRect();
    float w1 = paint.MeasureText(test, ref bounds);
    Console.WriteLine("===w1:" + w1);
    //Console.WriteLine("===bounds.Width" + bounds.Width);
    
    float w2 = paint.MeasureText(test);
    Console.WriteLine("===w1:" + w2);
    
  • Hi Jarvan,

    thank you for fast answer. I need not only the text width but the text height too, so I sould use the bounds because the simple MeasureText don't get back the text height.
    But I don't understand why bigger is the text width than the bound rectangle width? The opposite would be logical, wouldn't?
    And in this case the bounds are are less with 2 pixel then text size (width and height)? There is other process to get the text height? Or should I use the bouds and decrease then with 2 pixels?

    Thank you!

  • YelinzhYelinzh Member, Xamarin Team Xamurai

    Or should I use the bouds and decrease then with 2 pixels?

    No. The two 'test' string are different. Difference for 'this' is 3 pixels, 'text' is 2 pixels.

    string test_1 = "this";
    string test_2 = "text";
    ...
    
Sign In or Register to comment.