如果您需要绘制那么多图像,最好的办法是使用面板控件并通过处理OnPaint事件或者更好地处理绘图:创建一个继承自Panel控件并覆盖Paint方法的自定义控件.在线查看如何在.NET中创建自定义绘制控件的示例.
不要尝试使用Image控件或其他此类控件创建数百个图像,因为它会增加很多开销.
在Paint方法中,您可以使用DrawImage函数根据不同的状态(即选中或未选中)绘制椅子.您可以将椅子的状态存储在内存中的一维或二维数组中,然后在Paint方法中循环绘制每个椅子,根据其索引在屏幕上计算椅子的位置:
for(int chairIndex = 0; chairIndex < chairsCount; chairIndex++)
{
// compute the on-screen position of each chair
chairX = (chairIndex % chairsPerLine) * chairWidh;
chairY = (chairIndex / chairsPerLine) * chairHeight;
// and read the current state from the array
chairState = chairsArray[chairIndex];
// then draw the chair image in the graphics context
switch(chairState)
{
case /* SELECTED */
.. DrawImage(selectedImage, new Point(chairX, chairY));
case /* NOT-SELECTED */
.. DrawImage(nonSelectedImage, new Point(chairX, chairY));
}
}
Run Code Online (Sandbox Code Playgroud)
当用户单击一把椅子以在内存中切换它的状态时,您还必须处理鼠标事件以"命中测试".
// compute chairIndex based on mouse position (for hit-test)
chairIndex = mouseX / chairWidth + (mouseY / chairHeight) * chairsPerLine;
// then toggle state accordingly
Run Code Online (Sandbox Code Playgroud)
上面的代码片段假设您之前已经定义了一些变量,您已将不同的椅子图像加载到两个或多个变量中,并且您正在使用一维数组来存储主席状态.