C #: comparable pixel width text displayed in browser

I am trying to estimate the width in a pixel if the text will be displayed in Chrome using C # for a specific font (Arial 18px) in the tool that I am creating.

Comparison of my results with this tool (uses a browser to visualize the width): http://searchwilderness.com/tools/pixel-length/ line:

"Lorem ipsum dolor sit amet, consectetur adipiscing elit." 

Calculated as a width of 439 pixels.

But with this code in C #, I get 445px:

 var font = new Font("Arial", 18, FontStyle.Regular, GraphicsUnit.Pixel); var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; var size = TextRenderer.MeasureText(text, font, new Size(int.MaxValue, int.MaxValue), TextFormatFlags.NoPadding); 

Can I change my code to look like a browser?

I tried to display a label with font and text and compare with the rendering of the browser that they correspond to (+/- 1px).

+7
c #
source share
2 answers

Instead, you can use GDI + with StringFormat.GenericTypographic :

 var font = new System.Drawing.Font("Arial", 18, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; var graphics = System.Drawing.Graphics.FromHwnd(IntPtr.Zero); var size = graphics.MeasureString(text, font, int.MaxValue, System.Drawing.StringFormat.GenericTypographic); 

See also: fooobar.com/questions/134514 / ...

+3
source share

The most reliable way is to create a database of character widths issued by the client. This is far from trivial, measuring all the characters for each unique font, variations (bold / italics), size, scaling factors, browser and platform.

To avoid this, it would be wiser to do the rendering on the client, where the actual values ​​can be found using the equivalent getTextWidth ().

0
source share

All Articles