【问题标题】:How to resize from the center of element?如何从元素的中心调整大小?
【发布时间】:2011-02-23 17:42:35
【问题描述】:

我想用动画显示新窗口,将大小从 0 放大到 300。在 Loaded 事件中,我输入了以下代码:

DoubleAnimation heightAnim = new DoubleAnimation(0,300,TimeSpan.FromSeconds(1));
BeginAnimation(HeightProperty,heightAnim);

DoubleAnimation WidthAnim = new DoubleAnimation(0,300,TimeSpan.FromSeconds(1));
BeginAnimation(WidthProperty,WidthAnim);

此代码工作正常。但是构建从窗口的左上角开始,并向右和向下扩展,直到它达到 300 * 300 大小。 我希望它从中心开始并从那里扩展到所有 4 个方面。 我该怎么做?

附言在尝试Jogy 回答后,我意识到获得这种效果的更好方法是在 ScaleX 和 ScaleY 上应用动画,而不是在窗口大小上应用动画。因为当窗口大小的动画时,用户将只能看到部分内容,直到它达到全尺寸。 你觉得......怎么样 ?有什么更好的方法?

提前致谢!

【问题讨论】:

  • 以前没用过WPF,但是在openGL等中实现的方法是将“pivot”移到中心,然后进行缩放。 WPF 中必须有这样的东西。

标签: wpf animation


【解决方案1】:

为了得到这个效果,我意识到最好使用ScaleTransform。在Loaded 事件上,代码应该是这样的:

ScaleTransform scaleTransform = new ScaleTransform();

'grid' 是 Window 下的元素,它的 HorizontalElignmentVerticalElignment 设置为 'Center'

grid.LayoutTransform = scaleTransform;

DoubleAnimation heightAnim = new DoubleAnimation(0,1,TimeSpan.FromSeconds(1));
scaleTransform.BeginAnimation(ScaleTransform.ScaleYProperty,heightAnim);

DoubleAnimation WidthAnim = new DoubleAnimation(0,1,TimeSpan.FromSeconds(1));
scaleTransform.BeginAnimation((ScaleTransform.ScaleXProperty,WidthAnim);

【讨论】:

    【解决方案2】:

    为 Top 和 Left 属性再添加两个动画,如下所示:

      DoubleAnimation topAnim = new DoubleAnimation(this.Top, this.Top - 150, TimeSpan.FromSeconds(1));
      BeginAnimation(TopProperty, topAnim);
    
      DoubleAnimation leftAnim = new DoubleAnimation(this.Left, this.Left - 150, TimeSpan.FromSeconds(1));
      BeginAnimation(LeftProperty, leftAnim);
    

    您可能还希望通过将动画放在情节提要中来同步动画。

    【讨论】:

    • 好答案!但是在尝试之后,我意识到我需要的是其他方法。与其更改窗口大小,不如在窗口内面板的 ScaleX 和 ScaleY 上应用动画。
    猜你喜欢
    • 1970-01-01
    • 2017-08-05
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 2017-07-28
    相关资源
    最近更新 更多