Jump to content
Xtreme .Net Talk

Recommended Posts

Posted
I'm drawing some text with the Graphics object DrawString function, a Rectangle and a StringFormat object. I'd 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 StringFormat's Alignment and LineAlignment properties, or is there an easier way?
Posted
I don't understand the question. You specify the location when you call DrawString. What specific aspect of the rendered text do you want to measure?

 

Well, here's the code I have:

 

 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. I'm just querying whether I need the Select Cases stuff at the end or whether there's a simpler way to calculate TextRect.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...