2012-02-19 195 views
0

我想繪製一個簡單的圓形並通過編碼將其移動到X,Y軸上的定義位置。如何繪製一個圓形並將其作爲動畫在C#中移動WPF

例如;

在WPF窗口上會有2個按鈕,並且在0,0(x,y)上會有一個圓。當我點擊第一個按鈕時,它將轉到X = 150和Y = 40。但是形狀必須順利地進入。我的意思是我不希望它在當前位置失去知覺並出現在確定的位置上。我希望它去那裏。我應該怎麼做?你能解釋我的步驟嗎?如果可能的話,一些示例代碼?

更新的代碼:

int X = 0; 
    int Y = 0; 

    public bool inside = true; 

    private void Button_Click_1(object sender, RoutedEventArgs e) 
    { 

     if (inside) 
     { 
      DoubleAnimation animatex = new DoubleAnimation(); 
      animatex.To = X++; 
      // animatex.Duration = new Duration(TimeSpan.FromSeconds(1)); 
      // animatex.RepeatBehavior = RepeatBehavior.Forever; 
      el.BeginAnimation(Canvas.LeftProperty, animatex); 

      DoubleAnimation animatey = new DoubleAnimation(); 
      animatey.To = Y++; 
      // animatey.RepeatBehavior = RepeatBehavior.Forever; 
      el.BeginAnimation(Canvas.TopProperty, animatey); 
     } 
    } 

回答

0

XAML是像 <Canvas> <Ellipse Width="10" Height="10" Canvas.Left="0" Canvas.Top="0" Fill="Black" x:Name="el"/> </Canvas> 點擊按鈕的事件是這樣的

enter image description here

希望這會工作。我已經嘗試過,它的工作。

+0

請參閱[這裏](http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks)關於如何格式化代碼塊。你肯定不會永遠重複動畫,對吧?圓圈只需移動一次到目標位置。 – Clemens 2012-02-19 17:04:23

+0

感謝您的解決方案。對於Clemens;實際上,我會改進代碼,並且我會製作4個箭頭,左右下移,每當我點擊其中一個時,它將一直持續下去,直到我用另一個按鈕結束移動。似乎我會在if循環中逐個增加animatex和animatey – Samet 2012-02-19 17:56:16

+0

@ Ethicallogics或其他人:您能否檢查我在上面更新的代碼中所做的錯誤。我想繞圈移動,直到我改變if條件。但它不是那樣工作的。它每次點擊按鈕時都有效。 – Samet 2012-02-20 18:06:30

0

或僅在XAML:

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="Auto"/> 
     <RowDefinition /> 
    </Grid.RowDefinitions> 
    <StackPanel> 
     <Button Content="Move it"> 
      <Button.Triggers> 
       <EventTrigger RoutedEvent="Button.Click" > 
        <BeginStoryboard> 
         <Storyboard Storyboard.TargetName="theEllipse" Duration="00:00:05"> 
          <DoubleAnimation From="-5" To="145" Storyboard.TargetProperty="(Canvas.Left)"/> 
          <DoubleAnimation From="-5" To="35" Storyboard.TargetProperty="(Canvas.Top)"/> 
         </Storyboard> 
        </BeginStoryboard> 
       </EventTrigger> 
      </Button.Triggers> 
     </Button> 
    </StackPanel> 
    <Border Margin="10" Grid.Row="1"> 
     <Canvas> 
      <Ellipse x:Name="theEllipse" Width="10" Height="10" Fill="BlueViolet" Canvas.Left="-5" Canvas.Top="-5" /> 
     </Canvas> 
    </Border> 
</Grid> 

搜尋有關使用故事板的位置或其他地方的信息。

+0

你能檢查我在上面更新的代碼中有什麼問題嗎?我想繞圈移動,直到我改變if條件。但它不是那樣工作的。它每次點擊按鈕時都有效。謝謝。 – Samet 2012-02-20 18:09:06

+0

Samet,提出問題並不是很好的做法,然後在您有一個或多個有用或正確的答案後再更改它。請接受答案並提出一個新問題。 – Phil 2012-02-20 18:26:26

+0

好的,謝謝。我不知道。這裏是另一個鏈接:http://stackoverflow.com/questions/9366754/mo​​ving-a-drawn-circle-to-settled-position-in-c-sharp-wpf – Samet 2012-02-20 18:54:36

相關問題