【问题标题】:Move a shape in WinForm在 WinForm 中移动形状
【发布时间】:2017-06-22 15:47:36
【问题描述】:

我想在 WinForm 中移动一个形状。我正在使用以下算法实现它:

virtual public void Move(Graphics g)
{
    Center.X += _dx;
    if (Center.X - Size / 2 < 0)
    {
        _dx = _dx * -1;
    }
    else if (Center.X + Size / 2 > Form1.CanvasWidth)
    {
        _dx = _dx * -1;
    }

    Center.Y += _dy;
    if (Center.Y - Size / 2 < 0)
    {
        _dy = _dy * -1;
    }
    else if (Center.Y + Size / 2 > Form1.CanvasHeigth)
    {
        _dy = _dy * -1;
    }
    Draw(g, _currColor);
}

dx = 1dy = 1。对象根据需要移动。但我现在想将速度控制在 100 像素 - 每秒 1000 像素之间。我尝试更新计时器的间隔来实现这一点,但我没有看到任何重大变化。

myTimer.Interval = 1000/SpeedPx;

其中SpeedPx 是介于 100 - 1000 之间的值。

private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
    Form1 mainForm = Application.OpenForms.OfType<Form1>().SingleOrDefault();
    using (var g = mainForm.CreateGraphics())
    {
        g.Clear(mainForm._background);
        mainForm._shapes[mainForm._shapeIndex].Move(g);
    } 
}

我的鼠标点击事件中的以下几行:

 myTimer.Interval = 1000/SpeedPx;
 myTimer.Start();

【问题讨论】:

  • 我们看不到您的计时器实际在做什么。显示所有相关代码。
  • Graphics 对象从何而来? SpeedPx 是介于 100 - 1000 之间的值,这使得 Interval 介于 1 和 10 之间,但最小值为 15-25! (计时器不能再快了!!)
  • @TaW 我应该如何实现每秒 100 - 1000 像素之间的速度?
  • 更改速度增量以满足您的需要。对于 25ms = 40fps,它必须是 100/40 或 1000/40。我建议跟踪浮点变量中的位置!
  • 改变 dy & dx 的值也可以用来修改速度。

标签: c# winforms


【解决方案1】:

如果是 System.Timer,则 Timer 间隔以毫秒为单位,因此 1000 / 1000 .. 1000 / 100 给您 1 到 10 毫秒,普通人不会看到太大差异。

【讨论】:

  • 其实你会,但系统根本做不到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
  • 1970-01-01
  • 2014-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多