C#: Pixel width matching text rendered in a browser

I'm trying to estimate the widths in pixel if a text would be rendered in Chrome by using C# for a specific font (Arial 18px) in a tool that I'm creating.

Comparing my results with this tool (uses the browser to render the width): http://searchwilderness.com/tools/pixel-length/ the string:

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

Is calculated to be 439 pixels wide.

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 modify my code so it renders similar to the browser?

I've tried to output a label with the font and text and compared with browser rendering they do match (+/- 1px).


You can use GDI+ with StringFormat.GenericTypographic instead:

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: https://stackoverflow.com/a/6404811


The most foolproof way is to build a database of client-rendered character widths. It's far from trivial, measuring all characters for each unique font, variation (bold/italic), size, scaling factors, browser, and platform.

To avoid this, it might be more sensible to do render logic at the client, where actual values can be found using an equivalent to getTextWidth().

链接地址: http://www.djcxy.com/p/31636.html

上一篇: C ++中的静态和动态内存分配

下一篇: C#:像素宽度匹配在浏览器中呈现的文本