Graphics DrawImage - ArgumentException:'参数无效。'

时间:2017-06-19 17:10:53

标签: c# winforms graphics

我有计时器,每秒在面板上添加新图像。首先,我创建我的全局变量Graphics g,在construcor中创建计时器并在那里启动计时器。在我的Panel方法中,我创建了Graphics对象(g = e.Graphics),然后在我的计时器方法中,我使用该g对象绘制新图像。无法找到问题所在,这里是核心代码(程序在第一次调用时停止 - 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 个答案:

答案 0 :(得分:1)

您必须在OnPaint覆盖中绘制图像,因为Graphics对象将被处理掉。要重新绘制表单,您可以调用Refresh。另外,看看您的图像路径是否正确。

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);
    }
}