Drawing line “slowly” programmatically with wpf

2019-08-02 08:24发布

问题:

I have multiple points and I want to draw lines connecting that points with WPF, but I want to see them drawing slowly, and I need to do that programmatically, how can I do that?
Thanks.

回答1:

You can try something like this:

<Grid>
    <Grid.Triggers>
        <EventTrigger RoutedEvent="MouseDown">
            <EventTrigger.Actions>
                <BeginStoryboard>
                    <Storyboard TargetName="MyLine">
                        <DoubleAnimation Storyboard.TargetProperty="X2" To="100" Duration="0:0:5"/>
                        <DoubleAnimation Storyboard.TargetProperty="Y2" To="100" Duration="0:0:5"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger.Actions>
        </EventTrigger>
    </Grid.Triggers>
        <Line X1="10" Y1="10" X2="20" Y2="20" Stroke="Black" Name="MyLine"/>
</Grid>

When you click on the line, you'll see it grow. You can attach starting this storyboard to whatever event or code you want, I just used a mousedown for demonstration purposes.

If you want to draw multiple lines, you can do something like this:

<Grid>
    <Grid.Triggers>
        <EventTrigger RoutedEvent="Loaded">
            <EventTrigger.Actions>
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="Line1" Storyboard.TargetProperty="X2" To="100" Duration="0:0:5"/>
                        <DoubleAnimation Storyboard.TargetName="Line1" Storyboard.TargetProperty="Y2" To="100" Duration="0:0:5"/>
                        <DoubleAnimation Storyboard.TargetName="Line2" Storyboard.TargetProperty="X2" To="200" Duration="0:0:5" BeginTime="0:0:5"/>
                        <DoubleAnimation Storyboard.TargetName="Line2" Storyboard.TargetProperty="Y2" To="0" Duration="0:0:5" BeginTime="0:0:5"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger.Actions>
        </EventTrigger>
    </Grid.Triggers>
        <Line X1="10" Y1="10" X2="10" Y2="10" Stroke="Black" Name="Line1"/>
    <Line X1="100" Y1="100" X2="100" Y2="100" Stroke="Black" Name="Line2"/>
</Grid>

And, of course, it's quite possible to construct these storyboards on the fly if you can't declare them ahead of time in XAML.



标签: c# wpf drawing