UWP滑块的动画缩略图

时间:2019-03-26 08:20:42

标签: c# windows uwp win-universal-app uwp-xaml

我在UWP应用中使用Slider XAML控件。每当我们点击滑块并更改其值时,我都希望滑块在从旧位置移动到新位置时仅显示平移动画。如何实现?

1 个答案:

答案 0 :(得分:1)

您可以使用属性来获取最后一个值,并播放动画以将值从最后一个值设置为当前值。

在xaml中添加滑块

    <Slider x:Name="Slider" Value="{x:Bind Value,Mode=TwoWay}"/>

在MainPage中添加DependencyProperty。

    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
        "Value", typeof(double), typeof(MainPage), new PropertyMetadata(default(double), (s
            , e) =>
        {
            ((MainPage) s)._lastValue = (double) e.OldValue;
        }));

    public double Value
    {
        get => (double) GetValue(ValueProperty);
        set => SetValue(ValueProperty, value);
    }

    private double _lastValue;

Value可以设置可以启动情节提要的_lastValue

在MainPage代码中为Slider添加PointerPressedEvent和PointerReleasedEvent即可处理。

    public MainPage()
    {
        InitializeComponent();
        Slider.AddHandler(PointerPressedEvent, new PointerEventHandler(Slider_OnPointerPressed), true);
        Slider.AddHandler(PointerReleasedEvent, new PointerEventHandler(Slider_OnPointerReleased), true);
    }

我将ClickPoint保存在Slider_OnPointerPressed中,然后将当前点比较在Slider_OnPointerReleased中。用户可以单击应该开始动画的滑块,然后拖动不应该开始动画的拇指。

    private void Slider_OnPointerPressed(object sender, PointerRoutedEventArgs e)
    {
        var slider = (Slider) sender;

        ClickPoint = e.GetCurrentPoint(slider).Position;
    }

    private Point ClickPoint { set; get; }

    private void Slider_OnPointerReleased(object sender, PointerRoutedEventArgs e)
    {
        var slider = (Slider) sender;

        var point = e.GetCurrentPoint(slider).Position;

        var x = point.X - ClickPoint.X;
        var y = point.Y - ClickPoint.Y;
        var length = x * x + y * y;
        if (length < 10)
        {
            AnimationValue();
        }
    }

AnimationValue将开始动画。

    private void AnimationValue()
    {
        var storyboard = new Storyboard();

        var animation = new DoubleAnimation
        {
            From = _lastValue,
            To = Value,
            Duration = TimeSpan.FromSeconds(2),
            EasingFunction = new CubicEase(),
            EnableDependentAnimation = true
        };

        Storyboard.SetTarget(animation, Slider);
        Storyboard.SetTargetProperty(animation, "Value");

        storyboard.BeginTime = TimeSpan.Zero;
        storyboard.Children.Add(animation);

        storyboard.Begin();

        _storyboard = storyboard;
    }

您可以自定义DurationEasingFunction来更改时间。

github中的所有代码

如果您会读中文,请阅读我的blog,因为我的英语很差,我担心我无法准确告诉您我的意思。