2011-10-31 41 views
3

我畫的文字在VB.net:中心通過繪製文本

gfx.DrawString(_bText, New Font("Tahoma", 5), Brushes.Black, New Point(25, 5))

其中GFX是用我的控制圖形對象。 x點是正確的,但我需要y是當前控件的中心(垂直)。是否有捷徑可尋?

回答

1

TextRenderer有VerticalCenter標誌:

Dim r As New Rectangle(25, 0, myControl.ClientSize.Width - 25, _ 
           myControl.ClientSize.Height) 

Using myFont As New Font("Tahoma", 5) 
    TextRenderer.DrawText(gfx, _bText, myFont, r, _ 
         Color.Black, Color.Empty, _ 
         TextFormatFlags.VerticalCenter) 
End Using 
+1

TextFormatFlags.VerticalCenter和Horizo​​ntalCenter可以使用OR進行組合。在C#中是這樣的:TextFormatFlags.VerticalCenter | TextFormatFlags.Horizo​​ntalCenter – James

3

你需要看看Graphics.MeasureString方法

使用這個你可以找到你給它的背景文字的高度。然後你需要找到Y值來開始使用類似這樣的方式繪製文本:

(ControlHeight/2) - (TextHeight/2) 
+0

我在圖像上繪製文本,這使我比接受的答案更好的結果。 – madth3

2

使用接受StringFormat參數的DrawString重載。將其對齊屬性設置爲中心。