简体   繁体   中英

How do you calculate pixel size of string?

I have a string. I know the font family and the font size it is going to be displayed in. I need to know how many pixels the text will take up in the ui. So that I can determine whether to show another element. How would I do that?

I found a couple of things, but none of them were available in my Windows universal project. For example:

Edit:

This is not a web project.

I want to calculate the size it will take in the ui before it is in the ui.

I think you need to create a textblock in code and assign the desired text to it. Then you can get the actual height and width from it. See the below code

         TextBlock txt=new TextBlock();
        //set additional properties of textblock here . Such as font size,font family, width etc.
        txt.Text = "your text here";
        var height = txt.ActualHeight;
        var width = txt.ActualWidth;

You can do further operations based on this height and width

I am not saying this is the optimized solution .But this will work for you

在将字符串设置为文本/内容后,请尝试检查用于显示文本的控件的WidthHeight属性的值(例如,您的TextBox ),以决定是否显示另一个元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM