【问题标题】:Efficient way to move many Canvas Objects移动许多画布对象的有效方法
【发布时间】:2012-11-15 05:08:45
【问题描述】:

下面的代码从物理引擎中获取对象的所有位置和角度,并相应地更新每个对象。一旦对象之间有大量活动,它就会减慢。

我知道它不是物理引擎,因为我使用 OpenGL 编写了完全相同的东西,但我不能将它用于我的特定应用程序。

int bodyId = 0;
foreach (Shape shape in shapes)
{
    //Don't update sleeping objects because they are sleeping.
    //Waking them up would be terrible...
    //IGNORE THEM AT ALL COSTS!!
    if (physics.IsSleeping(bodyId))
    {
        ++bodyId;
        continue;
    }

    //Rotate transform
    RotateTransform rot = new RotateTransform(physics.GetAngle(bodyId));
    rot.CenterX = shape.Width / 2;
    rot.CenterY = shape.Height / 2;

    //Set the shape to rotate
    shape.RenderTransform = rot;

    //Body position
    Point bodyPos = physics.GetPosition(bodyId);
    Canvas.SetLeft(shape, bodyPos.X - shape.Width / 2);
    Canvas.SetTop(shape, bodyPos.Y - shape.Height / 2);

    ++bodyId;
}

我想知道是否有更有效的方法来完成上述操作,分为几个问题。

  1. 如果我调用 Canvas.SetLeft 和 Canvas.SetTop,UI 是否会在循环内开始呈现?或者如果不清楚,Canvas.SetLeft 和 Canvas.SetTop 函数究竟是如何工作的?

  2. 既然我已经在使用 RotateTransform,那么使用 TranslateTransform 会更好吗?

【问题讨论】:

    标签: c# wpf canvas shape


    【解决方案1】:
    1. 是的,每次您拥有的每个元素都会调用 SetTop() 和 SetLeft()。如果你想让一切更有效率,我会做以下事情。首先,您使用更新逻辑的更新函数,即计算对象应该在哪里,然后通过遍历对象来处理绘图,并且只使用一次 setLeft() 和 setTop() 而不是每次更新。
    2. 是的,它将为您节省一项操作。

    也许还有其他可以优化的地方。无需使用像 RotateTransform() 这样的 CPU 密集型矩阵运算,您可以通过将当前旋转状态保存在形状对象中来节省大量计算能力。此外,使用向量可能会帮助您提高性能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-12
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 2014-09-17
      • 1970-01-01
      相关资源
      最近更新 更多