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.
For Winforms:
I'm wanted to wrap text to draw it afterwards in my image. I tried the answer from @as-cii, but it didn't work in my case as expected. It always extends the given width of my line (maybe because I use it in combination with a Graphics object to draw the text in my image). Furthermore his answer (and related ones) just work for >.Net 4 frameworks. In framework .Net 3.5 there is no function Clear() for StringBuilder objects. So here is an edited version:
Because I'm working with a Graphics object I tried @Thorins solution. This worked for me much better, as it wraps my text right. But I made some changes so that you can give the method the required parameters. Also there was a bug: the last line was not added to the list, when the condition of the if-block in the for-loop was not reached. So you have to add this line afterwards. The edited Code looks like: