Подтвердить что ты не робот

Word переносит строку в несколько строк

Я пытаюсь передать конец строки в несколько строк. Каждая строка будет иметь ширину.

Например, я бы получил этот результат, если бы я обернул его в область шириной 120 пикселей.

Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Sed augue
velit, временный нелетучий sit amet,
dictum vitae lacus. В видеоролике ante
justo, ut accumsan sem. Донец
pulvinar, nisi nec sagittis, следовательно,
sem orci luctus velit, sed elementum
ligula ante nec neque. Pellentesque
житель morbi tristique senectus et
netus et malesuada fames ac turpis
экскреты. Etiam erat est, pellentesque
eget tincidunt ut, egestas in ante.
Nulla vitae вульгатный velit. Проин в
переходить нек. 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
адипизирующий уход. Mauris vel
аккуратный пурус. Proin quis enim

sem tempor vestibulum ac vitae augue.

4b9b3361

Ответ 1

static void Main(string[] args)
{
    List<string> lines = WrapText("Add some text", 300, "Calibri", 11);

    foreach (var item in lines)
    {
        Console.WriteLine(item);
    }

    Console.ReadLine();
}

static List<string> WrapText(string text, double pixels, string fontFamily, 
    float emSize)
{
    string[] originalLines = text.Split(new string[] { " " }, 
        StringSplitOptions.None);

    List<string> wrappedLines = new List<string>();

    StringBuilder actualLine = new StringBuilder();
    double actualWidth = 0;

    foreach (var item in originalLines)
    {
        FormattedText formatted = new FormattedText(item, 
            CultureInfo.CurrentCulture, 
            System.Windows.FlowDirection.LeftToRight,
            new Typeface(fontFamily), emSize, Brushes.Black);

        actualLine.Append(item + " ");
        actualWidth += formatted.Width;

        if (actualWidth > pixels)
        {
            wrappedLines.Add(actualLine.ToString());
            actualLine.Clear();
            actualWidth = 0;
        }
    }

    if(actualLine.Length > 0)
        wrappedLines.Add(actualLine.ToString());

    return wrappedLines;
}

Добавить библиотеки WindowsBase и PresentationCore.

Ответ 2

Следующий код, взятый из этого blogpost, поможет выполнить вашу работу.

Вы можете использовать его следующим образом:

string wordWrappedText = WordWrap( <yourtext>, 120 );

Обратите внимание, что код не мой, я просто сообщаю здесь основную функцию вашего товара.

protected const string _newline = "\r\n";

public static string WordWrap( string the_string, int width ) {
    int pos, next;
    StringBuilder sb = new StringBuilder();

    // Lucidity check
    if ( width < 1 )
        return the_string;

    // Parse each line of text
    for ( pos = 0; pos < the_string.Length; pos = next ) {
        // Find end of line
        int eol = the_string.IndexOf( _newline, pos );

        if ( eol == -1 )
            next = eol = the_string.Length;
        else
            next = eol + _newline.Length;

        // Copy this line of text, breaking into smaller lines as needed
        if ( eol > pos ) {
            do {
                int len = eol - pos;

                if ( len > width )
                    len = BreakLine( the_string, pos, width );

                sb.Append( the_string, pos, len );
                sb.Append( _newline );

                // Trim whitespace following break
                pos += len;

                while ( pos < eol && Char.IsWhiteSpace( the_string[pos] ) )
                    pos++;

            } while ( eol > pos );
        } else sb.Append( _newline ); // Empty line
    }

    return sb.ToString();
}

/// <summary>
/// Locates position to break the given line so as to avoid
/// breaking words.
/// </summary>
/// <param name="text">String that contains line of text</param>
/// <param name="pos">Index where line of text starts</param>
/// <param name="max">Maximum line length</param>
/// <returns>The modified line length</returns>
public static int BreakLine(string text, int pos, int max)
{
  // Find last whitespace in line
  int i = max - 1;
  while (i >= 0 && !Char.IsWhiteSpace(text[pos + i]))
    i--;
  if (i < 0)
    return max; // No whitespace found; break at maximum length
  // Find start of whitespace
  while (i >= 0 && Char.IsWhiteSpace(text[pos + i]))
    i--;
  // Return length of text before whitespace
  return i + 1;
}

Ответ 3

Вот версия, которую я придумал для своей игры XNA...

(Обратите внимание, что это фрагмент, а не правильное определение класса. Наслаждайтесь!)

using System;
using System.Text;
using Microsoft.Xna.Framework.Graphics;

public static float StringWidth(SpriteFont font, string text)
{
    return font.MeasureString(text).X;
}

public static string WrapText(SpriteFont font, string text, float lineWidth)
{
    const string space = " ";
    string[] words = text.Split(new string[] { space }, StringSplitOptions.None);
    float spaceWidth = StringWidth(font, space),
        spaceLeft = lineWidth,
        wordWidth;
    StringBuilder result = new StringBuilder();

    foreach (string word in words)
    {
        wordWidth = StringWidth(font, word);
        if (wordWidth + spaceWidth > spaceLeft)
        {
            result.AppendLine();
            spaceLeft = lineWidth - wordWidth;
        }
        else
        {
            spaceLeft -= (wordWidth + spaceWidth);
        }
        result.Append(word + space);
    }

    return result.ToString();
}

Ответ 4

Спасибо! Я беру метод из as-cii ответа с некоторыми изменениями, чтобы использовать его в формах Windows. Использование TextRenderer.MeasureText вместо FormattedText:

static List<string> WrapText(string text, double pixels, Font font)
{
string[] originalLines = text.Split(new string[] { " " }, 
    StringSplitOptions.None);

List<string> wrappedLines = new List<string>();

StringBuilder actualLine = new StringBuilder();
double actualWidth = 0;

foreach (var item in originalLines)
{
    int w = TextRenderer.MeasureText(item + " ", font).Width;
    actualWidth += w;

    if (actualWidth > pixels)
    {
        wrappedLines.Add(actualLine.ToString());
        actualLine.Clear();
        actualWidth = w;
    }

    actualLine.Append(item + " ");
}

if(actualLine.Length > 0)
    wrappedLines.Add(actualLine.ToString());

return wrappedLines;
}

И небольшое замечание: после проверки ширины следует поместить строку actualLine.Append(item + "");, потому что если actualWidth > пикселей, это слово должно быть в следующей строке.

Ответ 5

Для Winforms:

List<string> WrapText(string text, int maxWidthInPixels, Font font)
{
    string[] originalLines = text.Split(new string[] { " " }, StringSplitOptions.None);

    List<string> wrappedLines = new List<string>();

    StringBuilder actualLine = new StringBuilder();
    int actualWidth = 0;

    foreach (var item in originalLines)
    {
        Size szText = TextRenderer.MeasureText(item, font);

        actualLine.Append(item + " ");
        actualWidth += szText.Width;

        if (actualWidth > maxWidthInPixels)
        {
            wrappedLines.Add(actualLine.ToString());
            actualLine.Clear();
            actualWidth = 0;
        }
    }

    if (actualLine.Length > 0)
        wrappedLines.Add(actualLine.ToString());

    return wrappedLines;
}

Ответ 6

Вы можете получить (приблизительную) ширину строки из класса System.Drawing.Graphics, используя метод MeasureString(). Если вам нужна очень точная ширина, я думаю, вы должны использовать метод MeasureCharacterRanges(). Вот пример кода с использованием метода MeasureString(), чтобы сделать примерно то, что вы просили:

using System;
using System.Collections.Generic; // for List<>
using System.Drawing; // for Graphics and Font

private List<string> GetWordwrapped(string original)
{
    List<string> wordwrapped = new List<string>();

    Graphics graphics = Graphics.FromHwnd(this.Handle);
    Font font = new Font("Arial", 10);

    string currentLine = string.Empty;

    for (int i = 0; i < original.Length; i++)
    {
        char currentChar = original[i];
        currentLine += currentChar;
        if (graphics.MeasureString(currentLine, font).Width > 120)
        {
            // exceeded length, back up to last space
            int moveback = 0;
            while (currentChar != ' ')
            {
                moveback++;
                i--;
                currentChar = original[i];
            }
            string lineToAdd = currentLine.Substring(0, currentLine.Length - moveback);
            wordwrapped.Add(lineToAdd);
            currentLine = string.Empty;
        }
    }

    return wordwrapped;
}

Ответ 7

public static string GetTextWithNewLines(string value = "", int charactersToWrapAt = 35, int maxLength = 250)
        {
            if (string.IsNullOrWhiteSpace(value)) return "";

            value = value.Replace("  ", " ");
            var words = value.Split(' ');
            var sb = new StringBuilder();
            var currString = new StringBuilder();

            foreach (var word in words)
            {
                if (currString.Length + word.Length + 1 < charactersToWrapAt) // The + 1 accounts for spaces
                {
                    sb.AppendFormat(" {0}", word);
                    currString.AppendFormat(" {0}", word);
                }
                else
                {
                    currString.Clear();
                    sb.AppendFormat("{0}{1}", Environment.NewLine, word);
                    currString.AppendFormat(" {0}", word);
                }
            }

            if (sb.Length > maxLength)
            {
                return sb.ToString().Substring(0, maxLength) + " ...";
            }

            return sb.ToString().TrimStart().TrimEnd();
        }

Ответ 8

Мне нужно обернуть текст, чтобы нарисовать его потом по моему изображению. Я попробовал ответ от @as-cii, но он не работал в моем случае, как ожидалось. Он всегда расширяет заданную ширину моей линии (возможно, потому, что я использую ее в сочетании с объектом Graphics, чтобы нарисовать текст на моем изображении). Кроме того, его ответ (и связанные с ним) работает только в рамках .Net 4. В рамках .NET 3.5 нет функции Clear() для объектов StringBuilder. Итак, вот отредактированная версия:

    public static List<string> WrapText(string text, double pixels, string fontFamily, float emSize)
    {
        string[] originalWords = text.Split(new string[] { " " },
            StringSplitOptions.None);

        List<string> wrappedLines = new List<string>();

        StringBuilder actualLine = new StringBuilder();
        double actualWidth = 0;

        foreach (string word in originalWords)
        {
            string wordWithSpace = word + " ";
            FormattedText formattedWord = new FormattedText(wordWithSpace,
                CultureInfo.CurrentCulture,
                System.Windows.FlowDirection.LeftToRight,
                new Typeface(fontFamily), emSize, System.Windows.Media.Brushes.Black);

            actualLine.Append(wordWithSpace);
            actualWidth += formattedWord.Width;

            if (actualWidth > pixels)
            {
                actualLine.Remove(actualLine.Length - wordWithSpace.Length, wordWithSpace.Length);
                wrappedLines.Add(actualLine.ToString());
                actualLine = new StringBuilder();
                actualLine.Append(wordWithSpace);
                actualWidth = 0;
                actualWidth += formattedWord.Width;
            }
        }

        if (actualLine.Length > 0)
            wrappedLines.Add(actualLine.ToString());

        return wrappedLines;
    }

Поскольку я работаю с объектом Graphics, я попробовал решение @Thorins. Это работало для меня намного лучше, так как оно правильно меняет текст. Но я внес некоторые изменения, чтобы вы могли дать методу требуемые параметры. Также была ошибка: последняя строка не была добавлена ​​в список, когда условие if-блока в for-loop не было достигнуто. Поэтому вы должны добавить эту строку позже. Измененный код выглядит следующим образом:

    public static List<string> WrapTextWithGraphics(Graphics g, string original, int width, Font font)
    {
        List<string> wrappedLines = new List<string>();

        string currentLine = string.Empty;

        for (int i = 0; i < original.Length; i++)
        {
            char currentChar = original[i];
            currentLine += currentChar;
            if (g.MeasureString(currentLine, font).Width > width)
            {
                // exceeded length, back up to last space
                int moveback = 0;
                while (currentChar != ' ')
                {
                    moveback++;
                    i--;
                    currentChar = original[i];
                }
                string lineToAdd = currentLine.Substring(0, currentLine.Length - moveback);
                wrappedLines.Add(lineToAdd);
                currentLine = string.Empty;
            }
        }

        if (currentLine.Length > 0)
            wrappedLines.Add(currentLine);

        return wrappedLines;
    }