我正在尝试使用 picturebox
为了实现这一点,我创建了一个worker thread
来获得在线列车的位置。所以我在这里定义了线程:
private Thread workerThread = null;
private delegate void UpdateListBoxDelegate();
private UpdateListBoxDelegate UpdateListBox = null;
在Form_load
我称之为:
UpdateListBox = new UpdateListBoxDelegate(this.UpdateStatus);
// Initialise and start worker thread
workerThread = new Thread(new ThreadStart(this.GetOnlineTrain));
workerThread.Start();
我委托处理的方法是:
private void UpdateStatus()
{
foreach (TimeTable onlineTrain in OnlineTrainList.ToList())
{
if (lstSensorLeft.Count != 0 || lstSensorRight.Count != 0)
{
pictureBoxonlineTrain.Image = null;
DrawOnlineTrain();
}
else
{
pictureBoxonlineTrain.Image = null;
}
}
this.Invalidate();
}
GetOnlineTrain
获得在线列车的位置,如您所见:
public void GetOnlineTrain()
{
try
{
while (true)
{
TimeTableRepository objTimeTableREpository = new TimeTableRepository();
OnlineTrainList = objTimeTableREpository.GetAll().ToList();
objTimeTableREpository = null;
Invoke(UpdateListBox);
}
}
catch(Exception a)
{
}
}
最后的功能是在picturebox
上绘制在线列车:
public void DrawOnlineTrain()
{
Bitmap map;
using (map = new Bitmap(pictureBoxonlineTrain.Size.Width, pictureBoxonlineTrain.Size.Height))
{
if (OnlineTrainList.Count > 0)
{
using (Graphics graph = Graphics.FromImage(map))
{
foreach (TimeTable t in OnlineTrainList.ToList())
{
// graph.Dispose();
Rectangle rectTrainState = new Rectangle(t.XTrainLocation.Value - 3,
t.YTrainLocation.Value - 3,
15, 15);
graph.FillRectangle(RedBrush, rectTrainState);
graph.DrawString(t.TrainId.ToString(), pictureBoxonlineTrain.Font, Brushes.White, t.XTrainLocation.Value - 3, t.YTrainLocation.Value - 3);
pictureBoxonlineTrain.Image = map;
}
}
}
}
}
要首次绘制在线列车我在picturebox
上绘制了大小为x=A
和y=b
的列车(线路,车站......)地图,之后我创建了另一个{{ 1}}具有相同的大小,并使用此代码将第二个picturebox
放在第一个picturebox
上:
picturebox
但是当我在这行中运行我的应用程序时,我在 pictureBoxonlineTrain.Parent = pictureBoxMetroMap;
中获得了Parameter is not valid
。
map = new Bitmap(pictureBoxonlineTrain.Size.Width,pictureBoxonlineTrain.Size.Height);
堆栈跟踪:
DrawOnlineTrain
答案 0 :(得分:3)
我必须处理因为内存不足异常
不,你必须处理你不再使用的图像。正确的代码是:
Bitmap map = new Bitmap(pictureBoxonlineTrain.Size.Width, pictureBoxonlineTrain.Size.Height))
using (Graphics graph = Graphics.FromImage(map)) {
graph.Clear(this.BackColor);
foreach (TimeTable t in OnlineTrainList.ToList()) {
Rectangle rectTrainState = new Rectangle(...);
graph.FillRectangle(RedBrush, rectTrainState);
graph.DrawString(...);
}
}
if (pictureBoxonlineTrain.Image != null) pictureBoxonlineTrain.Image.Dispose();
pictureBoxonlineTrain.Image = map;