Graphics object MeasureString function

rbulph

Well-known member
Joined
Feb 17, 2003
Messages
343
Im drawing some text with the Graphics object DrawString function, a Rectangle and a StringFormat object. Id like to know where the text appears. The MeasureString function will give me the size of the text, but not its location. Do I have to work out its location based on the Rectangle and each possible value of the StringFormats Alignment and LineAlignment properties, or is there an easier way?
 
I dont understand the question. You specify the location when you call DrawString. What specific aspect of the rendered text do you want to measure?
 
marble_eater said:
I dont understand the question. You specify the location when you call DrawString. What specific aspect of the rendered text do you want to measure?

Well, heres the code I have:

Code:
 Protected Sub DrawText(ByVal gpcs As Graphics, ByVal br As Brush, ByVal s As String, ByVal R As RectangleF, ByVal ss As System.Drawing.StringFormat)

        Dim ff As Font = New System.Drawing.Font("Arial", 10)
        Dim hj As SizeF = gpcs.MeasureString(s, ff, New SizeF(R.Width, R.Height), ss)
      
        gpcs.DrawString(s, ff, br, R, ss)

        Dim RT As Integer

        Select Case ss.LineAlignment
            Case StringAlignment.Near
                RT = R.Top
            Case StringAlignment.Center
                RT = R.Top + R.Height / 2 - hj.Height / 2
            Case StringAlignment.Far
                RT = R.Bottom - hj.Height

        End Select

        Dim RL As Integer
        Select Case ss.Alignment
            Case StringAlignment.Near
                RL = R.Left
            Case StringAlignment.Center
                RL = R.Left + R.Width / 2 - hj.Width / 2
            Case StringAlignment.Far
                RL = R.Right - hj.Width

        End Select

        TextRect = New Rectangle(RL, RT, hj.Width, hj.Height)

    End Sub

When you call this override of DrawString you specify the rectangle that the text is to appear in and how the text is to be formatted within that rectangle, but not the position of the text. Im just querying whether I need the Select Cases stuff at the end or whether theres a simpler way to calculate TextRect.
 
Back
Top