游戏画面背景包含大量图片框,启动、最小化、移动后需要2-3秒才能完全显示背景。这段代码不适合我的目的吗?还有其他方法可以做到这一点吗?谢谢。这是代码:
public class gameArea
{
private Panel gameArea;
private MemoryStream ms;
public gameArea(Panel gameArea)
{
this.gameArea = gameArea;
}
public void setBackground()
{
byte[] b_grass = File.ReadAllBytes(ImageFile.grassBG);
byte[] b_tree = File.ReadAllBytes(ImageFile.tree);
byte[] b_sea = File.ReadAllBytes(ImageFile.sea);
// [650/50=13, 550/50=11]
int[,] tile_id = {
{ 1, 2, 0, 0, 0, 1, 1, 0, 1, 2, 1, 2, 0 },
{ 2, 1, 0, 1, 0, 1, 1, 2, 2, 2, 1, 2, 0 },
{ 1, 2, 0, 0, 0, 2, 1, 2, 1, 2, 1, 2, 1 },
{ 1, 2, 0, 0, 1, 0, 1, 0, 1, 2, 0, 0, 0 },
{ 1, 0, 2, 0, 0, 1, 1, 2, 1, 2, 1, 2, 0 },
{ 2, 2, 0, 1, 0, 1, 2, 1, 0, 2, 0, 1, 1 },
{ 1, 1, 2, 0, 0, 0, 1, 2, 1, 1, 2, 0, 0 },
{ 0, 2, 0, 2, 1, 2, 1, 0, 1, 2, 1, 2, 2 },
{ 1, 2, 0, 0, 0, 1, 0, 2, 0, 0, 1, 2, 0 },
{ 0, 2, 0, 1, 0, 1, 1, 2, 1, 2, 0, 0, 2 },
{ 1, 1, 1, 0, 0, 0, 1, 2, 1, 2, 1, 2, 0 }
};
// tree id = 1
// sea id = 2
this.ms = new MemoryStream(b_grass);
this.gameArea.BackgroundImage = Image.FromStream(ms);
this.gameArea.BackColor = System.Drawing.Color.Transparent;
for (int yIndex = 0, y = 0; y < this.gameArea.Height; y += 50, yIndex++)
{
for (int xIndex = 0, x = 0; x < this.gameArea.Width; x += 50, xIndex++)
{
switch (tile_id[yIndex, xIndex])
{
case 1:
{
setTile(b_tree, x, y);
break;
}
case 2:
{
setTile(b_sea, x, y);
break;
}
default:
{
break;
}
}
}
}
}
private void setTile(byte[] b_img, int x, int y)
{
this.ms = new MemoryStream(b_img);
PictureBox pic = new PictureBox();
pic.Image = Image.FromStream(ms);
pic.Size = new Size(50, 50);
pic.Location = new Point(x, y);
this.gameArea.Controls.Add(pic);
}
}
最佳答案
对于这种项目,恐怕你无能为力。 Visual C# 并不是真正为游戏而设计的,但有几种方法可以加快速度。
1.) 如果您的游戏不需要更改背景,请首先加载它,然后仅重置您需要的图片(可以在标签值中使用 bool 值来确定是否应该重绘。)
2.) 使用threading 。如果您启动 5 个线程,您的渲染速度可能会加快大约 3 倍。
3.) 在构造函数中将三个图像转换为 Image 对象,这样您就不需要为每个图 block 转换它们。
关于C# 图片框的加载时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12649774/