Aquí mi código, lo llamo desde un método:
private void MiMetodo( )
{
RichTextBox richTextBox = new RichTextBox(); // Crear una instancia de RichTextBox
Font font = new Font( "Microsoft Sans Serif", 12 );
int controlWidth = richTextBox.ClientSize.Width; // Ancho del RichTextBox (considerando el espacio del borde)
string textoJustificado = JustifyParagraph( RichTextBox1.Text, font, controlWidth );
RichTextBox1.Text = textoJustificado.ToString();
```}
private string JustifyParagraph(string text, Font font, int controlWidth)
{
```csharp
string[ ] lines = text.Split( new[ ] { Environment.NewLine }, StringSplitOptions.None );
StringBuilder result = new StringBuilder();
foreach ( string line in lines )
{
string justifiedLine = Justify( line, font, controlWidth );
result.AppendLine( justifiedLine );
}
return result.ToString().TrimEnd();
```}
private string Justify(string line, Font font, int controlWidth)
{
```csharp
string[ ] words = line.Split( ' ' );
StringBuilder justifiedLine = new StringBuilder();
int totalSpaces = controlWidth - TextRenderer.MeasureText( line, font ).Width;
int numWords = words.Length;
if ( numWords == 1 )
{
// Si solo hay una palabra, no es necesario justificarla
return line;
}
int spacesPerWord = totalSpaces / ( numWords - 1 );
int extraSpaces = totalSpaces % ( numWords - 1 );
for ( int i = 0; i < numWords; i++ )
{
justifiedLine.Append( words[ i ] );
if ( i < numWords - 1 )
{
int spacesToAdd = spacesPerWord + ( i < extraSpaces ? 1 : 0 );
if ( spacesToAdd > 0 ) // Evita agregar espacios negativos
{
justifiedLine.Append( ' ', spacesToAdd );
}
}
}
return justifiedLine.ToString();
```}