Reputation: 620
i'm trying to add an image to a C# project and it's always set to NULL and i get this warning 'Snake_Game.Form3.GFX' is never assigned to, and will always have its default value null. Here is what i tried to do.
private Graphics GFX;
public Form3()
{
InitializeComponent();
this.CreateGraphics();
}
And in other function i added this:
GFX.DrawImage(Bitmap.FromFile(@"C:\C#\Buton.png"), new Point(0, 0));
What should I do?
Upvotes: 1
Views: 671
Reputation: 216243
You need to initialize your Graphics object before use
public Form3()
{
InitializeComponent();
GFX = this.CreateGraphics();
}
then when you try to use it to DrawImage it is not null and you can call its methods.
However, let me say that this is the wrong way to go. You keep a Graphics object for the lifetime of your form consuming valuable system resources.
It is a good practice to create the object just before the usage and destroy it immediately after
So remove the initialization in the form constructor and the declaration at the global level
public Form3()
{
InitializeComponent();
}
and, when you need the object call
using(Graphics GFX = this.CreateGraphics())
{
GFX.DrawImage(Bitmap.FromFile(@"C:\C#\Buton.png"), new Point(0, 0));
.... // Other graphic code here
} // This close brace destroy the GFX object releasing its resources.
Some useful links for you
CreateGraphics
using statement
Upvotes: 2