Answer the question
In order to leave comments, you need to log in
How to implement the word wrap algorithm?
Hello!
There is a task to write a title on the picture, now I implemented it like this:
code:
...
// ТЕКСТ заголовок
ImageResizer.Plugins.Watermark.ImageLayer y = new ImageResizer.Plugins.Watermark.ImageLayer(c); //ImageLayer needs a Config instance so it knows where to locate images
string title = BL.Title;
t.Text = TextWrap(title, 38);
t.Fill = false;
t.Align = System.Drawing.ContentAlignment.MiddleCenter;
wp.NamedWatermarks["img"] = new ImageResizer.Plugins.Watermark.Layer[] { y };
wp.NamedWatermarks["text"] = new ImageResizer.Plugins.Watermark.Layer[] { t };
...
public string TextWrap(string myString, int n)
{
// int n - количество cимволов для строки (ширина картинки)
int length = myString.Length;
char[] arrayOfSimbols = myString.ToCharArray();
myString = "";
for (int i = 0; i < length / n; i++)
{
foreach (char z in arrayOfSimbols.Skip(i * n).Take(n).ToArray())
myString += z;
myString += Environment.NewLine;
}
//остаток прибавим в конец
foreach (char x in arrayOfSimbols.Skip(arrayOfSimbols.Count() - arrayOfSimbols.Count() % n).ToArray())
myString += x;
return myString;
}
public string TextWrap(string myString, int LengthRow)
{
int CurrentLengthRow = 0;
string ReadyRezult = "";
string [] TextArr = myString.Split(' ');
foreach (string Word in TextArr)
{
if( (CurrentLengthRow) + (Word.Length) < LengthRow)
{
ReadyRezult += Word + " ";
CurrentLengthRow += (Word.Length) + 1;
}
else
{
ReadyRezult += Environment.NewLine;
CurrentLengthRow = 0;
}
}
return ReadyRezult;
}
Answer the question
In order to leave comments, you need to log in
I would do the following:
1. Determine the optimal length of the line in characters
2. Cut by words so that the words remaining in the line in total do not exceed the maximum length of the line
3. Line up the lines by evenly adding spaces between the words in the line
Visually, this will look like width alignment in Word.
After splitting by words, it will look like this:
Политолог Бортник: скоро власть
придумает новых реформаторов, чтобы
...
Политолог Бортник: скоро власть
придумает новых реформаторов, чтобы
...
I don’t know how in .NET, but I remember WinAPI has a mechanism for determining the size in pixels for a block of text. As a result, we take the size of the gap, take the size of each word and calculate. And in this case it will work correctly with characters of different widths. And per character only for monospaced fonts.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question