How can I calculate the width of a string in Metro (without displaying it)?

混江龙づ霸主 提交于 2019-12-11 01:33:35

问题


I have failed to find a Windows Runtime equivalent to the following WPF code to measure the width of a string:

FormattedText formattedText = new FormattedText(in_string,in_culture,in_flowdir,in_font,in_sz,in_color);
string_width = formattedText.WidthIncludingTrailingWhitespace);

Does anybody know if it can be done in Metro?


回答1:


It is possible, I've found one method that gives useful measurements, but I am not sure it is the best way of doing it:

// Setup the TextBlock with *everything* that affects how it 
// will be drawn (this is not a complete example)
TextBlock^ tb = ref new TextBlock; 
tb->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Top; 
tb->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Left; 
tb->Height = in_height; 
tb->Text = text;

// Be sure to tell Measure() the correct dimensions that the TextBox 
// have to draw in!
tb->Measure(SizeHelper::FromDimensions(Parent->Width,Parent->Height)); 
text_width = tb->DesiredSize.Width;

My gut feeling is that there are situations in which this code will give an unexpected result.




回答2:


Try this:

private double stringWidth(string s, double fontSize)
    {
        if(s==" ")
            s = "\u00A0";  //this line wasn't required in silverlight but is now

        TextBlock t = new TextBlock()
        {
            FontSize = fontSize,
            Text = s
        };
        t.Measure(new Size(double.MaxValue, double.MaxValue));  //this line wasn't required in silverlight but is now
        return t.ActualWidth;
    }


来源:https://stackoverflow.com/questions/9126076/how-can-i-calculate-the-width-of-a-string-in-metro-without-displaying-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!