Measure a String without using a Graphics object?

前端 未结 5 1076
梦谈多话
梦谈多话 2020-11-27 19:57

I am using pixels as the unit for my font. In one place, I am performing a hit test to check if the user has clicked within the bounding rectangle of some text on screen. I

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 20:25

    You don't need to use the graphics object that you are using to render to do the measuring. You could create a static utility class:

    public static class GraphicsHelper
    {
        public static SizeF MeasureString(string s, Font font)
        {
            SizeF result;
            using (var image = new Bitmap(1, 1))
            {
                using (var g = Graphics.FromImage(image))
                {
                    result = g.MeasureString(s, font);
                }
            }
    
            return result;
        }
    }
    

    It might be worthwile, depending on your situation to set the dpi of the bitmap as well.

提交回复
热议问题