Graphics.FillRectangle - 参数无效

时间:2018-03-30 06:26:30

标签: c# .net exception

我想使用箭头在面板上移动玩家。我的面板有一个Paint事件:

private void panel1_Paint(object sender, PaintEventArgs e)
{
    var gameManager = new GameManager(this, e.Graphics);
}

GameManager.cs

public GameManager(Form1 gameForm, Graphics graphic)
{
    this.gameForm = gameForm;
    this.graphic = graphic;

    player = new Player(100, 100, graphic);
    gameForm.KeyUp += MovePlayer; // Event to handle KeyUpevent
}

private void MovePlayer(object sender, System.Windows.Forms.KeyEventArgs e)
{
     int x = 0, y = 0;

     switch (e.KeyCode)
     {
         case System.Windows.Forms.Keys.Down:
              y = 10;
              player.Move(x, y);
              break;
         }
     }
 }

Player.cs

private SolidBrush brush = new SolidBrush(Color.Black);

        public Player(int x, int y, Graphics graphic)
        {
            location = new Point(x, y);
            this.graphic = graphic;

            graphic.FillRectangle(brush, location.X, location.Y, 10, 10);
        }

        public void Move(int x, int y)
        {
            location.X += x;
            location.Y += y;

            graphic.FillRectangle(brush, location.X, location.Y, 10, 10); // Here I get an error
        }

问题:当调用播放器对象时(在构造函数上),播放器在Panel上正确生成。但是当我点击down arrow key时,我收到以下信息:

  

System.ArgumentException:参数无效

但所有参数似乎都是有效的,SolidBrush对象以及坐标和尺寸。有什么问题?

1 个答案:

答案 0 :(得分:0)

根据(MSDN)你不应该缓存Graphics对象。而是根据需要创建和处理它。

最简单的修改示例:

public Player(int x, int y, Form1 form)
{
    _form = form;
    location = new Point(x, y);
    graphic = form.CreateGraphics();
    graphic.FillRectangle(brush, location.X, location.Y, 10, 10);
    graphic.Dispose();
}

 public void Move(int x, int y)
 {
    location.X += x;
    location.Y += y;

    graphic = _form.CreateGraphics();
    graphic.FillRectangle(brush, location.X, location.Y, 10, 10); 
    graphic.Dispose();
 }

此外,您可能不应该在每次重绘时重新创建GameManager,但也许只是为了简单起见。