2011-11-15 43 views
1

我在我正在構建的紙牌遊戲應用程序中使用了三個畫布。其中之一是,有另外兩個爲孩子畫布(一個靜態和一個會旋轉)主畫布:WPF TranslateTransform從畫布中的旋轉對象到另一個畫布中的固定對象

Canvas Layout

在此示例應用程序,我想給RotatingEl移動對StaticEl的位置:

Start Point

當我點擊移動按鈕,它按預期工作:

End Point

現在,我想旋轉RotatingCanvas,仍然有RotatingEl移動到StaticEl位置,並調整轉速仍然匹配StaticEl的角度:

Rotated Canvas

當我嘗試它,它移動到錯誤位置:

End Location After Move

這裏是我的移動按鈕單擊代碼:

GeneralTransform generalTransformStaticEl = StaticEl.TransformToVisual(MainCanvas); 
     Point pointstatic = generalTransformStaticEl.Transform(new Point()); 
     GeneralTransform generalTransformRotEl = RotatingEl.TransformToVisual(MainCanvas); 
     Point pointrot = generalTransformRotEl.Transform(new Point()); 

     double distancecalcX = pointstatic.X - pointrot.X; 
     double distancecalcY = pointstatic.Y - pointrot.Y; 

     DoubleAnimation ELMoveY = new DoubleAnimation(); 

     ELMoveY.From = Canvas.GetTop(RotatingEl); 
     ELMoveY.To = Canvas.GetTop(RotatingEl)+(distancecalcY); 
     ELMoveY.Duration = new Duration(TimeSpan.FromSeconds(1.0)); 

     DoubleAnimation ELMoveX = new DoubleAnimation(); 

     ELMoveX.From = Canvas.GetLeft(RotatingEl); 
     ELMoveX.To = Canvas.GetLeft(RotatingEl)+(distancecalcX); 
     ELMoveX.Duration = new Duration(TimeSpan.FromSeconds(1.0)); 

     RotatingEl.BeginAnimation(Canvas.LeftProperty, ELMoveX); 
     RotatingEl.BeginAnimation(Canvas.TopProperty, ELMoveY); 

如何調整動畫的「To」以仍然將旋轉畫布的RotatingEl移動到靜態StaticEl的位置,並調整RotatingEl的旋轉以匹配StaticEl的方向?

回答

1

我找到了我自己的解決方案。萬一有人可能有興趣,這裏是更新後的代碼:

double foundangle = 0; 
     //verify an actual transform group is there before getting rotate angle 
     if (RotatingCanvas.RenderTransform.Value.ToString() != "Identity") 
     { 
      RotateTransform rt = (RotatingCanvas.RenderTransform as TransformGroup).Children[2] as RotateTransform; 
      foundangle = rt.Angle; 
     } 
     RotateTransform rottrans = new RotateTransform(foundangle*-1); 
     RotatingEl.RenderTransform = rottrans; 
     GeneralTransform generalTransformStaticEl = StaticEl.TransformToVisual(RotatingCanvas); 
     Point pointstatic = generalTransformStaticEl.Transform(new Point()); 

     DoubleAnimation ELMoveY = new DoubleAnimation(); 

     ELMoveY.From = Canvas.GetTop(RotatingEl); 
     ELMoveY.To = pointstatic.Y; 
     ELMoveY.Duration = new Duration(TimeSpan.FromSeconds(1.0)); 

     DoubleAnimation ELMoveX = new DoubleAnimation(); 

     ELMoveX.From = Canvas.GetLeft(RotatingEl); 
     ELMoveX.To = pointstatic.X; 
     ELMoveX.Duration = new Duration(TimeSpan.FromSeconds(1.0)); 

     RotatingEl.BeginAnimation(Canvas.LeftProperty, ELMoveX); 
     RotatingEl.BeginAnimation(Canvas.TopProperty, ELMoveY); 

的generalTransformStaticEl需要統籌從旋轉畫布代替非旋轉MainCanvas。對旋轉的調整僅僅是獲得旋轉畫布的當前旋轉角度並乘以-1以與靜態矩形對齊