Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Pixel width matching text rendered in a browser

Tags:

c#

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).

like image 688
Niels Bosma Avatar asked Jan 21 '16 20:01

Niels Bosma


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language?

C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.


1 Answers

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

like image 116
M. Buga Avatar answered Oct 05 '22 03:10

M. Buga