I developing a program like Word. For that I need to write strings into the same “line”, and I also want the ability to format each word/letter/sentence differently, controlling color, size, font, etc.
So I have to calculate the pixel length and height of a string, to put them into a line. But there is a problem with the function (Graphics) MeasureString, this function puts extra length infront/behind a string. This function has also has some problems with white space.
I tried a different StringFormater, but everytime they return too much length or not enough.
Does a function exist to write different formated strings on the Graphics object or a function to calculate the exact pixel length of a string?
First off, this is a fairly tricky problem to solve properly – you may be better off trying to find an existing control (e.g. the RichTextBox) that solves this for you.
That said if you do want to do this then this is more-or-less the correct way to solve this problem, however if you take a look at the MeasureString documentation you will note that the behaviour you are seeing is intentional
So it sounds to me like you should instead be using the Graphics.MeasureCharacterRanges Method instead.
Here is a sample I prepared that deals renders some text in two different colours. To try it out just paste it into a new form
This is what it looks like
Note that you need to be careful with clipping – GDI will "wrap" rendered text onto new lines for you by default, however this wont work any more, you will end up with something like this
Also if you try and print out text with different fonts / font sizes then the "bottom" of each of those fonts won’t line up where you expect it to. Try taking a look at Formatting text on a common baseline for some hints on how to deal with that.