Measure a String without using a Graphics object?

前端 未结 5 1085
梦谈多话
梦谈多话 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条回答
  •  猫巷女王i
    2020-11-27 20:41

    This example does great job of illustrating the use of FormattedText. FormattedText provides low-level control for drawing text in Windows Presentation Foundation (WPF) applications. You can use it to measure the Width of a string with a particular Font without using a Graphics object.

    public static float Measure(string text, string fontFamily, float emSize)
    {
        FormattedText formatted = new FormattedText(
            item, 
            CultureInfo.CurrentCulture, 
            System.Windows.FlowDirection.LeftToRight, 
            new Typeface(fontFamily), 
            emSize, 
            Brushes.Black);
    
        return formatted.Width;
    }
    

    Include WindowsBase and PresentationCore libraries.

提交回复
热议问题