I am trying to word wrap a string into multiple lines. Every line will have defined width.
For example I would get this result if I word wrap it to an area of 120 pixels in width.
Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Sed augue
velit, tempor non vulputate sit amet,
dictum vitae lacus. In vitae ante
justo, ut accumsan sem. Donec
pulvinar, nisi nec sagittis consequat,
sem orci luctus velit, sed elementum
ligula ante nec neque. Pellentesque
habitant morbi tristique senectus et
netus et malesuada fames ac turpis
egestas. Etiam erat est, pellentesque
eget tincidunt ut, egestas in ante.
Nulla vitae vulputate velit. Proin in
congue neque. Cras rutrum sodales
sapien, ut convallis erat auctor vel.
Duis ultricies pharetra dui, sagittis
varius mauris tristique a. Nam ut
neque id risus tempor hendrerit.
Maecenas ut lacus nunc. Nulla
fermentum ornare rhoncus. Nulla
gravida vestibulum odio, vel commodo
magna condimentum quis. Quisque
sollicitudin blandit mi, non varius
libero lobortis eu. Vestibulum eu
turpis massa, id tincidunt orci.
Curabitur pellentesque urna non risus
adipiscing facilisis. Mauris vel
accumsan purus. Proin quis enim nec
sem tempor vestibulum ac vitae augue.
Here's a version I came up with for my XNA game...
(Note that it's a snippet, not a proper class definition. Enjoy!)
You can get the (approximate) width of a string from the System.Drawing.Graphics class using the MeasureString() method. If you need a very precise width, I think you have to use the MeasureCharacterRanges() method. Here is some sample code using the MeasureString() method to do roughly what you asked for:
The following code, taken from this blogpost, will help to get your job done.
You can use it this way:
Please note that the code is not mine, I am just reporting here the main function for your commodity.
Thanks! I take metod from as-cii answer with some changes, for using it in windows forms. Using TextRenderer.MeasureText instead of FormattedText:
And a little remark: the line actualLine.Append(item + " "); need to be placed after checking width, because if actualWidth > pixels, this word must be in the next line.
Add
WindowsBase
andPresentationCore
libraries.