2011-09-21 9 views
5

Sto disegnando del testo su un oggetto System.Drawing.Graphics. Sto usando il metodo DrawString, con la stringa di testo, un Font, uno Brush, un limite RectangleF e uno StringFormat come argomenti.Giustifica il testo usando DrawString in C#

Guardando in StringFormat, ho trovato che posso impostare è Alignment proprietà Near, Center o Far. Tuttavia non ho trovato un modo per impostarlo su Justified. Come posso raggiungere questo obiettivo?

Grazie per il vostro aiuto!

risposta

1

Non esiste un modo integrato per farlo. Alcuni work-around sono menzionati in questa discussione:

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

Essi suggeriscono di usare una ignorato RichTextBox, sovrascrivendo la proprietà SelectionAlignment (vedi this page for how) e impostandola su Justify.

Le viscere della sostituzione ruotano attorno a questa chiamata 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); 

Non so quanto bene questo può essere integrato nel modello esistente (dato che presumo si sta disegnando più di testo), ma potrebbe Sii la tua unica opzione.

1

ho trovato :)

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

in breve - si può giustificare il testo in ogni riga separata quando si conosce la larghezza data di tutto il paragrafo:

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 

il resto è abbastanza 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. 
}