【问题标题】:Windows Forms / C#: only one object instance out of many will paintWindows 窗体/C#:许多对象实例中只有一个对象实例会绘制
【发布时间】:2009-11-13 08:52:55
【问题描述】:

问题来了:

我一直在做一个小游戏,怪物从主窗体的墙壁(边缘)反弹,它会游泳,但是当它应该迭代一个列表时,它只绘制每种类型的怪物他们每个人都调用他们的 OnPaint 和 Move 方法:

private void Pacmen_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    Rectangle rect = e.ClipRectangle;

    g.Clear(backgroundColor);

    foreach (Hydra h in hydraList) {
        h.OnPaint(e);
        h.Move(e);
    } // end foreach

    foreach (Ghost gh in ghostList) {
        gh.OnPaint(e);
        gh.Move(e);
    } // end foreach
}

这是鬼的方法:

public void OnPaint(PaintEventArgs e)
{
    Graphics g = e.Graphics;
    g.SmoothingMode = SmoothingMode.HighQuality;

    GraphicsPath path = new GraphicsPath();
    SolidBrush fillBrush = new SolidBrush(color);
    SolidBrush eyeBrush = new SolidBrush(Color.Black);

    path.AddArc(pos, (float)180, (float)180);
    path.AddLine((float)pos.Right, (float)(pos.Y + pos.Height / 2),
        (float)pos.Right, (float)pos.Bottom);
    path.AddLine((float)pos.Right, (float)pos.Bottom,
        (float)(pos.X + pos.Width / 2), (float)(pos.Bottom - radius / 2));
    path.AddLine((float)(pos.X + pos.Width / 2), (float)(pos.Bottom - radius / 2),
        (float)pos.Left, (float)pos.Bottom);
    path.AddLine((float)pos.Left, (float)pos.Bottom,
        (float)pos.Left, (float)(pos.Y + pos.Height / 2));

    g.FillPath(fillBrush, path);
    g.FillEllipse(eyeBrush, new Rectangle(pos.X + pos.Width / 4, pos.Y + pos.Height / 4, radius / 4, radius / 5));
    g.FillEllipse(eyeBrush, new Rectangle(pos.X + 3 * pos.Width / 4, pos.Y + pos.Height / 4, radius / 4, radius / 5));
} // end OnPaint

public void Move(PaintEventArgs e)
{
    pos.Offset(xSpeed, ySpeed);
}

知道为什么只有一个会出现吗?谢谢!

【问题讨论】:

  • 我认为这不值得回答,但您确实应该在调用 OnPaint 之间缓存 SolidBrushes - 将它们存储在类中的某个地方。他们也确实需要处理。
  • ...而且您也不应该一遍又一遍地重新创建路径...

标签: c# windows forms object


【解决方案1】:

您确定要给角色单独的起始位置和速度吗?也许他们都在画画,但在同一个地方?

【讨论】:

    【解决方案2】:

    您使用传递给Pacmen_Paint 的相同PaintEventArgs 为每个九头蛇和幽灵调用OnPaint。也许OnPaint 方法没有使用正确的Graphics 对象。

    【讨论】:

    • 我认为Pacmen_Paint 是实际的Paint 事件处理程序,因此Graphics 实例看起来适合用于所有绘图。
    • 好吧,我假设每个怪物都有自己的 Graphics 对象。
    【解决方案3】:

    尝试用简单的替换 Ghost 方法的主体:

    Console.WriteLine("Ghost at " +  pos.X + ", " + pos.Y);
    

    然后运行应用程序并检查 VS 中的输出窗口以查看它们的准确绘制位置。

    其他注释(其他人可能已经评论过):

    1. Use the using constructPaint 方法中处理 Brushes 和其他一次性图形对象,或者缓存它们并使您的 GhostHydra 对象 implement IDisposable 在不再需要它们时处理它们.

    2. 1234563这样,您只需创建一次图形对象(再次在 using 构造内)。

    【讨论】:

    • 谢谢,原来它们是在相互重叠的……我以为它们都是随机的。
    • 很高兴您发现了问题。您还应该考虑其他注意事项,以使您的应用程序运行更快并使用更少的内存。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多