【UWP】實現一個波浪進度條

h82258652發表於2022-04-04

好久沒寫 blog 了,一個是忙,另外一個是覺得沒啥好寫。廢話不多說,直接上效果圖:

可能看到這波浪線你覺得會很難,但看完這篇 blog 後應該你也會像我一樣恍然大悟。圖上的圖形,我們可以考慮是由 3 條直線和 1 條曲線組成。直線沒什麼難的,難的是曲線。在曲線這一領域,我們有一種特殊的曲線,叫貝塞爾曲線。

在上面這曲線,我們可以對應到的是三次方貝塞爾曲線,它由 4 個點控制,起點、終點和兩個控制點。這裡我找了一個線上的 demo:https://www.bezier-curve.com/

調整控制點 1(紅色)和控制點 2(藍色)的位置我們可以得到像最開始的圖那樣的波浪線了。

另外,我們也可以注意到一個性質,假如起點、終點、控制點 1 和控制點 2 都在同一條直線上的話,那麼我們這條貝塞爾曲線就是一條直線。

按最開始的圖的動畫,我們最終狀態是一條直線,顯然就是需要這 4 個點都在同一直線上,然而在動畫過程中,我們需要的是一條曲線,也就是說動畫過程中它們不會在同一直線上了。我們也可以注意到,在波浪往上漲的時候,左邊部分是凸起來的,而右半部分是凹進去的。這對應了控制點 1 是在直線以上,而控制點 2 在直線以下。那麼如何在動畫裡做到呢,很簡單,使用緩動函式就行了,讓控制點 1 的值更快到達最終目標值,讓控制點 2 的值更慢到達最終目標值即可。(當然,單純使用時間控制也行,在這裡我還是用緩動函式)

理論已經有了,現在讓我們開始編碼。

 

新建一個 UWP 專案,然後我們建立一個模板控制元件,叫 WaveProgressBar。之所以不繼承自 ProgressBar,是因為 ProgressBar 上有一個 IsIndeterminate 屬性,代表不確定狀態,我們的 WaveProgressBar 並不需要,簡單起見,我們還是從模板控制元件開始。

接下來我們修改 Generic.xaml 中的控制元件模板程式碼

<Style TargetType="local:WaveProgressBar">
        <Setter Property="Background" Value="LightBlue" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:WaveProgressBar">
                    <Viewbox Stretch="Fill">
                        <Path
                            Width="100"
                            Height="100"
                            Fill="{TemplateBinding Background}">
                            <Path.Data>
                                <PathGeometry>
                                    <PathGeometry.Figures>
                                        <PathFigure StartPoint="0,100">
                                            <PathFigure.Segments>
                                                <LineSegment x:Name="PART_LineSegment" Point="0,50" />
                                                <BezierSegment
                                                    x:Name="PART_BezierSegment"
                                                    Point1="35,25"
                                                    Point2="65,75"
                                                    Point3="100,50" />
                                                <LineSegment Point="100,100" />
                                            </PathFigure.Segments>
                                        </PathFigure>
                                    </PathGeometry.Figures>
                                </PathGeometry>
                            </Path.Data>
                        </Path>
                    </Viewbox>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

這裡我使用了一個 Viewbox 以適應 Path 縮放。Path 大小我們定義為 100x100,然後先從左下角 0,100 開始繪製,繪製一條直線到 0,50,接下來繪製我們的貝塞爾曲線,Point3 是終點 100,50,最後我們繪製了一條直線從 100,50 到 100,100。另外因為 PathFigure 預設就是會自動封閉的,所以我們不需要畫 100,100 到 0,100 的這一條直線。當然以上這些點的座標都會在執行期間發生變化是了,這裡這些座標僅僅只是先看看效果。

加入如下程式碼到我們的頁面:

<local:WaveProgressBar Width="200" Height="300" />

執行程式應該會看到如下效果:

 

接下來我們就可以考慮我們的進度 Progress 屬性了,這裡我定義 0 代表 0%,1 代表 100%,那 0.5 就是 50% 了。定義如下依賴屬性:

    public class WaveProgressBar : Control
    {
        public static readonly DependencyProperty ProgressProperty = DependencyProperty.Register(
            nameof(Progress), typeof(double), typeof(WaveProgressBar), new PropertyMetadata(0d, OnProgressChanged));

        public WaveProgressBar()
        {
            DefaultStyleKey = typeof(WaveProgressBar);
        }

        public double Progress
        {
            get => (double)GetValue(ProgressProperty);
            set => SetValue(ProgressProperty, value);
        }

        private static void OnProgressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            throw new NotImplementedException();
        }
    }

由於我們要對 Path 裡面的點進行動畫,所以先在 OnApplyTemplate 方法中把它們拿出來。

    [TemplatePart(Name = LineSegmentTemplateName, Type = typeof(LineSegment))]
    [TemplatePart(Name = BezierSegmentTemplateName, Type = typeof(BezierSegment))]
    public class WaveProgressBar : Control
    {
        public static readonly DependencyProperty ProgressProperty = DependencyProperty.Register(
            nameof(Progress), typeof(double), typeof(WaveProgressBar), new PropertyMetadata(0d, OnProgressChanged));

        private const string BezierSegmentTemplateName = "PART_BezierSegment";
        private const string LineSegmentTemplateName = "PART_LineSegment";

        private BezierSegment _bezierSegment;
        private LineSegment _lineSegment;

        public WaveProgressBar()
        {
            DefaultStyleKey = typeof(WaveProgressBar);
        }

        public double Progress
        {
            get => (double)GetValue(ProgressProperty);
            set => SetValue(ProgressProperty, value);
        }

        protected override void OnApplyTemplate()
        {
            _lineSegment = (LineSegment)GetTemplateChild(LineSegmentTemplateName);
            _bezierSegment = (BezierSegment)GetTemplateChild(BezierSegmentTemplateName);
        }

        private static void OnProgressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            throw new NotImplementedException();
        }
    }

接著我們可以考慮動畫部分了,這裡應該有兩個地方會呼叫到動畫,一個是 OnProgressChanged,Progress 值變動需要觸發動畫。另一個地方是 OnApplyTemplate,因為控制元件第一次出現時需要將 Progress 的值立刻同步上去(不然 Progress 跟看上去的不一樣),所以這個是瞬時的動畫。

配合最開始的理論,我們大致可以編寫出如下的動畫程式碼:

        private void PlayAnimation(bool isInit)
        {
            if (_lineSegment == null || _bezierSegment == null)
            {
                return;
            }

            var targetY = 100 * (1 - Progress);
            var duration = new Duration(TimeSpan.FromSeconds(isInit ? 0 : 0.7));

            var storyboard = new Storyboard();

            var point1Animation = new PointAnimation
            {
                EnableDependentAnimation = true,
                Duration = duration,
                To = new Point(0, targetY),
                EasingFunction = new BackEase
                {
                    Amplitude = 0.5
                }
            };
            Storyboard.SetTarget(point1Animation, _lineSegment);
            Storyboard.SetTargetProperty(point1Animation, nameof(_lineSegment.Point));
            storyboard.Children.Add(point1Animation);

            var point2Animation = new PointAnimation
            {
                EnableDependentAnimation = true,
                Duration = duration,
                To = new Point(35, targetY),
                EasingFunction = new BackEase
                {
                    Amplitude = 1.5
                }
            };
            Storyboard.SetTarget(point2Animation, _bezierSegment);
            Storyboard.SetTargetProperty(point2Animation, nameof(_bezierSegment.Point1));
            storyboard.Children.Add(point2Animation);

            var point3Animation = new PointAnimation
            {
                EnableDependentAnimation = true,
                Duration = duration,
                To = new Point(65, targetY),
                EasingFunction = new BackEase
                {
                    Amplitude = 0.1
                }
            };
            Storyboard.SetTarget(point3Animation, _bezierSegment);
            Storyboard.SetTargetProperty(point3Animation, nameof(_bezierSegment.Point2));
            storyboard.Children.Add(point3Animation);

            var point4Animation = new PointAnimation
            {
                EnableDependentAnimation = true,
                Duration = duration,
                To = new Point(100, targetY),
                EasingFunction = new BackEase
                {
                    Amplitude = 0.5
                }
            };
            Storyboard.SetTarget(point4Animation, _bezierSegment);
            Storyboard.SetTargetProperty(point4Animation, nameof(_bezierSegment.Point3));
            storyboard.Children.Add(point4Animation);

            storyboard.Begin();
        }

對於 OnApplyTemplate 的瞬時動畫,我們直接設定 Duration 為 0。

接下來 4 個點的控制,我們通過使用 BackEase 緩動函式,配上不同的強度(Amplitude)來實現控制點 1 先到達目標,然後是起點和終點同時到達目標,最後控制點 2 到達目標。

 

最後 WaveProgressBar 的完整程式碼應該是這樣的:

    [TemplatePart(Name = LineSegmentTemplateName, Type = typeof(LineSegment))]
    [TemplatePart(Name = BezierSegmentTemplateName, Type = typeof(BezierSegment))]
    public class WaveProgressBar : Control
    {
        public static readonly DependencyProperty ProgressProperty = DependencyProperty.Register(
            nameof(Progress), typeof(double), typeof(WaveProgressBar), new PropertyMetadata(0d, OnProgressChanged));

        private const string BezierSegmentTemplateName = "PART_BezierSegment";
        private const string LineSegmentTemplateName = "PART_LineSegment";

        private BezierSegment _bezierSegment;
        private LineSegment _lineSegment;

        public WaveProgressBar()
        {
            DefaultStyleKey = typeof(WaveProgressBar);
        }

        public double Progress
        {
            get => (double)GetValue(ProgressProperty);
            set => SetValue(ProgressProperty, value);
        }

        protected override void OnApplyTemplate()
        {
            _lineSegment = (LineSegment)GetTemplateChild(LineSegmentTemplateName);
            _bezierSegment = (BezierSegment)GetTemplateChild(BezierSegmentTemplateName);

            PlayAnimation(true);
        }

        private static void OnProgressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var obj = (WaveProgressBar)d;
            obj.PlayAnimation(false);
        }

        private void PlayAnimation(bool isInit)
        {
            if (_lineSegment == null || _bezierSegment == null)
            {
                return;
            }

            var targetY = 100 * (1 - Progress);
            var duration = new Duration(TimeSpan.FromSeconds(isInit ? 0 : 0.7));

            var storyboard = new Storyboard();

            var point1Animation = new PointAnimation
            {
                EnableDependentAnimation = true,
                Duration = duration,
                To = new Point(0, targetY),
                EasingFunction = new BackEase
                {
                    Amplitude = 0.5
                }
            };
            Storyboard.SetTarget(point1Animation, _lineSegment);
            Storyboard.SetTargetProperty(point1Animation, nameof(_lineSegment.Point));
            storyboard.Children.Add(point1Animation);

            var point2Animation = new PointAnimation
            {
                EnableDependentAnimation = true,
                Duration = duration,
                To = new Point(35, targetY),
                EasingFunction = new BackEase
                {
                    Amplitude = 1.5
                }
            };
            Storyboard.SetTarget(point2Animation, _bezierSegment);
            Storyboard.SetTargetProperty(point2Animation, nameof(_bezierSegment.Point1));
            storyboard.Children.Add(point2Animation);

            var point3Animation = new PointAnimation
            {
                EnableDependentAnimation = true,
                Duration = duration,
                To = new Point(65, targetY),
                EasingFunction = new BackEase
                {
                    Amplitude = 0.1
                }
            };
            Storyboard.SetTarget(point3Animation, _bezierSegment);
            Storyboard.SetTargetProperty(point3Animation, nameof(_bezierSegment.Point2));
            storyboard.Children.Add(point3Animation);

            var point4Animation = new PointAnimation
            {
                EnableDependentAnimation = true,
                Duration = duration,
                To = new Point(100, targetY),
                EasingFunction = new BackEase
                {
                    Amplitude = 0.5
                }
            };
            Storyboard.SetTarget(point4Animation, _bezierSegment);
            Storyboard.SetTargetProperty(point4Animation, nameof(_bezierSegment.Point3));
            storyboard.Children.Add(point4Animation);

            storyboard.Begin();
        }
    }

修改專案主頁面如下:

<Grid>
        <local:WaveProgressBar
            Width="200"
            Height="300"
            Progress="{Binding ElementName=Slider, Path=Value}" />

        <Slider
            x:Name="Slider"
            Width="200"
            Margin="0,0,0,20"
            HorizontalAlignment="Center"
            VerticalAlignment="Bottom"
            Maximum="1"
            Minimum="0"
            StepFrequency="0.01" />
    </Grid>

此時再執行的話,你就會看到如本文開頭中動圖的效果了。

 

本文的程式碼也可以在這裡找到:https://github.com/h82258652/UWPWaveProgressBar

相關文章