Graphics.MeasureString

  • Thread starter Thread starter Anil Gupte
  • Start date Start date
A

Anil Gupte

I copied the following almost directly from
http://msdn2.microsoft.com/en-us/library/6xe5hazb.aspx

Dim instance As Graphics

Dim text As String

'Dim strfont As Font

Dim returnValue As SizeF

text = "asdas asd asd asd"

Dim strfont As New Font("Arial", 16)

returnValue = instance.MeasureString(text, strfont)


and it still does not work! I get an error saying Oject reference is not
set to an intance of an object. I have tried all kinds of combinations, but
it still will not work. In the documentation i.e. dynamic help the
implementation seems to be different.

Can anyone tell me how to implement this?

Thanx,
 
Hi Anil,

The variable "instance" is declared but not assigned, and you get an
NullReferenceException.
If you are inside a Paint event handler, set e.Graphics to it.

Otherwise, you could use Control.CreateGraphics.

Using instance As Graphics = someControl.CreateGraphics()
' code here
End Using

Thi
http://thith.blogspot.com/
 
Anil said:
and it still does not work! I get an error saying Oject reference is not
set to an intance of an object. I have tried all kinds of combinations, but
it still will not work. In the documentation i.e. dynamic help the
implementation seems to be different.

Hi Anil,

The error is correct :-)
When you just write "Dim instance As Graphics" you don't have an
instance of this class. When you debug it you see that the value of
'instance' is nothing. Normally it must be "Dim instance as new
Graphics" but because Graphics has no constructors, this won't work
too.
So you have to get the graphics object from another object which can
create a graphics object for you (e.g. a Control)

Example ( Get Graphics object from a textbox) :
Dim myGraphics as Graphics
myGraphics = TextBox1.createGraphics()
 
Yes, only 4 minutes. :-) But thanx to both of you. I now understand how to
do it but seems exceptionally convoluted. I had inf act tried the New
keyword and it still had not worked. A class that you can't really use? How
like Microsoft....

Anyway thanx again to both.
 
Back
Top