0
votes

I have timer which adds new image on the panel every second. First i create my global variable Graphics g, create timer in the construcor and start timer there. In my Panel method i create Graphics object (g = e.Graphics) and then in my timer method i use that g object to draw new image. Can't find what's the problem, here's the core code (program stops when on the first call - g.DrawImage()):

public partial class MyClass: Form
{
private Timer addImage;

private Image img;

private Graphics g;
private Point pos;

public MyClass()
{
    InitializeComponent();

    img = Image.FromFile("C:/image.png");
    pos = new Point(100, 100);

    addImage = new Timer()
    {
        Enabled = true,
        Interval = 3000,
    };
    addImage.Tick += new EventHandler(AddImage);
    addImage.Start();
}

private void MyPanel_Paint(object sender, PaintEventArgs e)
{
    g = e.Graphics;
}

private void AddImage(Object myObject, EventArgs myEventArgs)
{
    g.DrawImage(img, pos); // ArgumentException: 'Parameter is not valid.'

    MyPanel.Invalidate();
}
}
1
Put a breakpoint where the code blows up and verify that your inputs are what you are expecting them to be. Also, put a try/catch around the code in AddImage so you can inspect the exception and see what's really going on. I am assuming you are using a version of Visual Studio.Joel Priddy
Files should never be placed in the root directory.LarsTech
Never try to cache a Graphics object! Either draw into a Bitmap bmp using a Graphics g = Graphics.FromImage(bmp) or in the Paint event of a control, using the e.Graphics parameter.. - Also: location and speeing of your path are suspect.TaW

1 Answers

1
votes

You have to draw your image in the OnPaint override because the Graphics object will be disposed. To redraw the form you can call Refresh. Also look that your that your path to the image is correct.

public partial class MyClass : Form
{
    private readonly Image _image;
    private readonly Point _position;
    private bool _isImageVisible;

    public MyClass()
    {
        InitializeComponent();

        _image = Image.FromFile(@"C:\img.png");
        _position = new Point(100, 100);

        var addImageCountdown = new Timer
        {
            Enabled = true,
            Interval = 3000,
        };
        addImageCountdown.Tick += new EventHandler(AddImage);
        addImageCountdown.Start();
    }

    private void AddImage(Object myObject, EventArgs myEventArgs)
    {
        _isImageVisible = true;
        Refresh();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if(_isImageVisible)
        { 
            e.Graphics.DrawImage(_image, _position);
        }
        base.OnPaint(e);
    }
}