![](/img/trans.png)
[英]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.