【问题标题】:When moving rectangle with background image, the image repeats itself, instead of redrawing移动带有背景图像的矩形时,图像会自行重复,而不是重绘
【发布时间】:2019-06-28 19:09:07
【问题描述】:

我正在尝试制作一个游戏,其中主要对象 Hero 在地图上移动并杀死敌人。

该对象表示为带有背景图像的矩形。

我找到了几种正确导入图像的解决方案,但似乎都不是很好,所有这些都只是在矩形内重复图像。 更准确地说,有一些“隐藏”的重复图像,当我移动矩形时,它只是将它们揭开。

   Image image = new Bitmap(Properties.Resources.Untitled);
   TextureBrush tBrush = new TextureBrush(image);
   g.FillRectangle(tBrush, X, Y, characterWidth, characterHeight);

当我只画一个矩形并使用Move 函数时,一切都很好, 每次我移动时,他都会重新绘制自己。但是当我导入背景图片时,一切都变得一团糟。

Move函数的实现:

public void Move(int width, int height, String direction, List<Obstacles.Rectangle> rectangles)
        {
            int oldX = this.X;
            int oldY = this.Y;
            if (direction == "UP")
            {
                this.Y -= 10;
                if (IsCollided(rectangles) || this.Y < 0)
                {
                    this.Y = oldY;
                }
            }
            if (direction == "DOWN")
            {
                this.Y += 10;
                if (IsCollided(rectangles) || this.Y > height)
                {
                    this.Y = oldY;
                }
            }
            if (direction == "LEFT")
            {
                this.X -= 10;
                if (IsCollided(rectangles) || this.X < 0)
                {
                    this.X = oldX;
                }
            }
            if (direction == "RIGHT")
            {
                this.X += 10;
                if (IsCollided(rectangles) || this.X > width)
                {
                    this.X = oldX;
                }

            }


        }

【问题讨论】:

  • 这是 Unity 内部的吗?
  • 忘了说,Windows 窗体。
  • 你也可以分享Move function吗?
  • @SᴇM Move 只是增加/减少 X/Y 坐标,没什么特别的。
  • 可能是因为你没有在 TextureBrush 构造函数中使用WrapMode.ClampDrawImageUnscaled 有其缺点。但是,当然,如果您对此感到满意,那就太好了。

标签: c# winforms


【解决方案1】:

使用 Windows 窗体,您需要注意使控件无效和重新绘制控件。此外,如果表面不时闪烁,使用双缓冲可以防止它。

无效: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.invalidate?view=netframework-4.8

OnPaint: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.onpaint?view=netframework-4.8

【讨论】:

  • 我知道Invalidate,我之前说过,当我没有用背景图像填充形状时,只是一个普通的矩形,一切都很好,很平滑。我也在使用双缓冲。
  • 从哪里运行绘制图像的代码(什么方法/事件和什么容器)?它应该来自容器(用作画布的控件)的 OnPaint 方法。
  • 我找到了解决方案,我使用DrawImageUnscaled 而不是FillRectangle。正如我之前提到的,当我不使用背景图像时很好,这意味着从OnPaint调用该方法。
猜你喜欢
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 2013-07-16
  • 2014-07-01
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多