繁体   English   中英

如何优化表单重绘

[英]How to optimize Form repaint

尝试编写一个简单的 2D 游戏。 这样做:

public interface GameObject
{
    Bitmap Picture  { get; }
    int OffsetX     { get; }
    int OffsetY     { get; }
}

此处 Picture 属性返回应为当前 object 绘制的图片。

public static class Game
{
    public class MapIndexer
    {
        public GameObject this[int x, int y]
        {
            get => map[y, x];
            set => map[y, x] = value;
        }
    }

    private static MapIndexer indexer;
    public static MapIndexer Map
    {
        get => indexer ?? (indexer = new MapIndexer());
    }

    static GameObject[,] map = new GameObject[,]
    {
        { null, null, null },
        { null, null, null },
        { null, null, null }
    };

    public static int MapWidth
    {
        get => map.GetLength(1);
    }
    public static int MapHeight
    {
        get => map.GetLength(0);
    }
}

包含 Map 索引器并用于进一步开发的游戏 class。 [y, x] 索引是像笛卡尔坐标一样访问 Map ,否则我会得到倒置的尺寸。 数组中的 NULL 只是一个填充物(即我的游戏中的草,它什么都不做,只需要填充 map,所以我认为没有理由为它创建一个单独的 class)。 还从 GameObject 接口创建了一个简单的 Player class ,它只返回要绘制的图片。 这是实际的油漆代码:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    for (int y = 0; y < Game.MapHeight; y++)
        for (int x = 0; x < Game.MapWidth; x++)
        {
            e.Graphics.DrawImage(Properties.Resources.Grass, new Point(x * size, y * size));
            if (Game.Map[x, y] is not null)
                e.Graphics.DrawImage(Game.Map[x, y].Picture, new Point(x * size + Game.Map[x, y].OffsetX, y * size + Game.Map[x, y].OffsetY));
        }
}

所以当我做一些动作时,我会使表单无效并获得下一帧。 对我来说看起来很奇怪,实际上是因为在执行动作时,每次重绘操作时画面都会闪烁。 测试用的 animation 是玩家移动,每 200ms 发生一次,并不多。 所以问题是:如何优化绘图使其看起来很流畅,或者我的代码设计实际上一开始就很糟糕?

您遇到的效果与性能并没有真正的关系。 您所看到的很可能是在重绘之前清除屏幕的效果。 您应该研究一个称为“双缓冲”的概念。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM