2012-12-17 13 views
6

Sto cercando di realizzare testi incorniciate (utilizzando Windows Form), ad esempio:Come trovare la larghezza di stringa in C# (in pixel)

enter image description here

L'altezza è sempre lo stesso, perché le mie corde sono meno di 20 caratteri. Che dire della larghezza? C'è un modo per farlo automaticamente?

+0

duplcato possibile: http://stackoverflow.com/questions/7714022/how-to-get-a-string-width – Default

+0

Possibile duplicato di [Come posso convertire una lunghezza di stringa in un'unità pixel?] (Http: //stackoverflow.com/questions/451903/how-can-i-convert-a-string-length-to-a-pixel-unit) –

risposta

10

Usa Graphics.MeasureString()

Da MSDN: http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx

private void MeasureStringMin(PaintEventArgs e) 
{ 
    // Set up string. 
    string measureString = "Measure String"; 
    Font stringFont = new Font("Arial", 16); 

    // Measure string. 
    SizeF stringSize = new SizeF(); 
    stringSize = e.Graphics.MeasureString(measureString, stringFont); 

    // Draw rectangle representing size of string. 
    e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height); 

    // Draw string to screen. 
    e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0)); 
} 
4

Se non avete voglia di trattare con l'EventHandler Paint, si potrebbe provare la classe TextRenderer. Ha un metodo statico identico al metodo "MeasureString" nella risposta sopra. In questa classe si chiama MeasureText tuttavia.

Problemi correlati