简体   繁体   中英

how to draw a circle and move it as an animation in C# WPF

I would like to draw a simple circle and move it to the defined position on X,Y axis by coding.

For example;

There will be 2 buttons on WPF window and there will be a circle on 0,0(x,y). When I clicked on the 1st button, it will go to X = 150 and Y= 40. But the shape has to go there smoothly. I mean I dont want it to be disapear at the current position and appear on the defined position. I want it to go there. How should I do this? Can you explain me the steps? and if possible some example code ?

UPDATED CODE:

    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);
        }
    }

xaml is something like <Canvas> <Ellipse Width="10" Height="10" Canvas.Left="0" Canvas.Top="0" Fill="Black" x:Name="el"/> </Canvas> Click event of button is something like this

在此处输入图片说明

Hope this will work. I have tried it and it worked.

Or in XAML only:

<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>

Search for information on the use of Storyboard here or elsewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM