[英]Bitmap - ArgumentException: “Parameter is not valid.” (intermittent)
[英]Graphics DrawImage - ArgumentException: 'Parameter is not valid.'
我有计时器,它每秒钟在面板上添加一个新图像。 首先,我创建我的全局变量Graphics g,在构造函数中创建计时器,然后在其中启动计时器。 在我的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();
}
}
您必须在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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.