Results 1 to 3 of 3

Thread: [RESOLVED] Calculate a String's size on screen

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Nov 2006
    Location
    Dublin, Ireland
    Posts
    24

    Resolved [RESOLVED] Calculate a String's size on screen

    I have a custom button that needs to use graphics.drawstring for its text property. Does anybody know how to get what the string’s length will be when it's on the screen. It'd be great if you where able to view the code from the class Buttonbase to see how it's done.

    At the moment I just have a hidden label that gets added to the same parent container as the button and then read the labels width property

    Any suggestions?
    Ger

  2. #2
    Hyperactive Member
    Join Date
    Aug 2005
    Location
    Lancashire UK
    Posts
    375

    Re: Calculate a String's size on screen

    You need to use the graphics measureString method.


    vb Code:
    1. Private Sub Button1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Button1.Paint
    2.         Dim strTest As String = "Test String"
    3.         Dim g As Graphics = e.Graphics
    4.         Dim sz As SizeF
    5.         'get the size of the string
    6.         sz = g.MeasureString(strTest, Me.Font)
    7.         'draw it where we want.
    8.         g.DrawString(strTest, Me.Font, Brushes.Black, 5, 5)
    9.     End Sub
    Last edited by Tinbeard; Mar 14th, 2007 at 04:07 AM.
    If my post helps , please feel free to rate it

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Nov 2006
    Location
    Dublin, Ireland
    Posts
    24

    Re: Calculate a String's size on screen

    Quote Originally Posted by Tinbeard
    You need to use the graphics measureString method.


    vb Code:
    1. Private Sub Button1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Button1.Paint
    2.         Dim strTest As String = "Test String"
    3.         Dim g As Graphics = e.Graphics
    4.         Dim sz As SizeF
    5.         'get the size of the string
    6.         sz = g.MeasureString(strTest, Me.Font)
    7.         'draw it where we want.
    8.         g.DrawString(strTest, Me.Font, Brushes.Black, 5, 5)
    9.     End Sub
    Perfect,

    Thanks for your help.
    I don't know how i missed that function in graphics.

    Ger

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width