2012-12-17 16 views
6

Próbuję osiągnąć teksty oprawione (z wykorzystaniem Windows Forms), np:Jak znaleźć szerokość struny w języku C# (w pikselach)

enter image description here

wysokość jest zawsze taka sama, bo moje słowa są mniej niż 20 znaków. A co z szerokością? Czy jest jakiś sposób, aby uzyskać to automatycznie?

+0

możliwe duplipcate: http://stackoverflow.com/questions/7714022/how-to-get-a-string-width – Default

+0

Możliwy duplikat [Jak mogę przekonwertować długość łańcucha na jednostkę piksela?] (Http: //stackoverflow.com/questions/451903/how-can-i-convert-a-string-length-to-a-pixel-unit) –

Odpowiedz

10

Zastosowanie Graphics.MeasureString()

Od 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

Jeśli nie masz ochoty do czynienia z eventhandler farbą, można spróbować klasę TextRenderer. Ma statyczną metodę, która jest identyczna z metodą "MeasureString" w powyższej odpowiedzi. W tej klasie nazywa się to jednak MeasureText.

Powiązane problemy