适合特定宽度的字符串长度

Ian*_*Ian 9 wpf wpf-controls

我确定我错过了一些明显的东西,我有一个区域,我打算在其中绘制文字.我知道它(区域)的高度和宽度.我想知道宽度中有多少个字符/单词,最好是字符.第二个问题,如果线太长我想画第二行,所以我想我也需要得到文本的高度,包括它认为正确的垂直填充?

我也想知道逆,即我可以在特定宽度中适合多少个字符.

我认为WPF不受像素约束这一事实会对答案有所影响吗?

最终,我计划在文本中嵌入不规则形状图像周围的文字.

任何正确方向的指针都会很棒.

谢谢

Bro*_*ass 17

对于WPF,您可以使用FormattedText类来计算给定文本字符串将使用的宽度 - 它将取决于实际文本.

例:

FormattedText formattedText = new FormattedText("Hello Stackoverflow", 
                                                System.Globalization.CultureInfo.GetCultureInfo("en-us"), 
                                                FlowDirection.LeftToRight, 
                                                new Typeface("Arial"), FontSize =14, Brushes.Black);
double textWidth = formattedText.Width;
Run Code Online (Sandbox Code Playgroud)

获取给定宽度的子字符串(简化):

string text  = GetSubStringForWidth("Hello Stackoverflow", 55);
...
public string GetSubStringForWidth(string text, double width)
{
    if (width <= 0)
        return "";

    int length = text.Length;
    string testString;

    while(true)//0 length string will always fit
    {
        testString = text.Substring(0, length);
        FormattedText formattedText = new FormattedText(testString, 
                                                        CultureInfo.GetCultureInfo("en-us"), 
                                                        FlowDirection.LeftToRight, 
                                                        new Typeface("Arial"), 
                                                        FontSize = 14, 
                                                        Brushes.Black);
        if(formattedText.Width <= width)
            break;
        else
            length--;
    }
    return testString;
}
Run Code Online (Sandbox Code Playgroud)