2011-09-21 85 views
5

Estoy dibujando texto en un objeto System.Drawing.Graphics. Estoy utilizando el método DrawString, con la cadena de texto, un Font, un Brush, un RectangleF delimitador, y un StringFormat como argumentos.Justificación de texto con DrawString en C#

Mirando hacia StringFormat, he descubierto que puedo establecer que es Alignment propiedad a Near, Center o Far. Sin embargo, no he encontrado una forma de configurarlo en Justified. ¿Cómo puedo conseguir esto?

¡Gracias por tu ayuda!

Respuesta

1

No hay una forma incorporada de hacerlo. Algunas soluciones temporales se mencionan en este tema:

http://social.msdn.microsoft.com/Forums/zh/winforms/thread/aebc7ac3-4732-4175-a95e-623fda65140e

Sugieren usar un reemplaza RichTextBox, anulando la propiedad SelectionAlignment (ver this page for how) y se establece a Justify.

Las tripas de la anulación giran en torno a esta llamada PInvoke:

PARAFORMAT fmt = new PARAFORMAT(); 
fmt.cbSize = Marshal.SizeOf(fmt); 
fmt.dwMask = PFM_ALIGNMENT; 
fmt.wAlignment = (short)value; 

SendMessage(new HandleRef(this, Handle), // "this" is the RichTextBox 
    EM_SETPARAFORMAT, 
    SCF_SELECTION, ref fmt); 

No está seguro de lo bien que se puede integrar en el modelo existente (ya que supongo que está dibujando más de texto), pero podría ser tu única opción

1

lo encontré :)

http://csharphelper.com/blog/2014/10/fully-justify-a-line-of-text-in-c/

en pocas palabras - se puede justificar el texto en cada línea por separado cuando se conoce el ancho dado de todo el párrafo:

float extra_space = rect.Width - total_width; // where total_width is the sum of all measured width for each word 
int num_spaces = words.Length - 1; // where words is the array of all words in a line 
if (words.Length > 1) extra_space /= num_spaces; // now extra_space has width (in px) for each space between words 

el resto es bastante intuitivo:

float x = rect.Left; 
float y = rect.Top; 
for (int i = 0; i < words.Length; i++) 
{ 
    gr.DrawString(words[i], font, brush, x, y); 

    x += word_width[i] + extra_space; // move right to draw the next word. 
} 
Cuestiones relacionadas