如果我們希望制作的動畫效果像現實生活中的運動一樣平滑, 比如汽車的啟動與停止總有一個加速或減速的過程, 那麼我們有必要研究一下"緩動"
緩入: 速度逐漸增加的過程,比如汽車的啟動
如果我們用曲線上的點的斜率表示速度,那麼在數學上它對應了下面這樣的曲線:
緩出:速度逐漸減小的過程,比如汽車的停止
在數學上它對應了下面的曲線
就加速運動而言, 根據以下位置與加速度等公式
我們可以得到,任意時刻的速度等於總的路程乘以當前時間與總時間的比值的平方, 而總的路程實際將相當與WPF中Animation的To與From的差值, 當前時間與總時間的比值實際上相當與WPF中animationClock.CurrentProgress.Value值.
除此之外,我們發現,曲線的指數越大,點的斜率變化越快,那麼加速度也就越大.
有了這些知識,我們可以很好的模擬加速運動了
參考以下代碼
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Media.Animation;
using System.Windows;
namespace EaseMoveDemo
{
public class EaseMoveAnimation : DoubleAnimationBase
{
public static readonly DependencyProperty FromProperty = DependencyProperty.Register(
"From", typeof(double?), typeof(EaseMoveAnimation), new PropertyMetadata(null));
public static readonly DependencyProperty ToProperty = DependencyProperty.Register(
"To", typeof(double?), typeof(EaseMoveAnimation), new PropertyMetadata(null));
public static readonly DependencyProperty PowerProperty = DependencyProperty.Register(
"Power", typeof(double?), typeof(EaseMoveAnimation), new PropertyMetadata(null));
public double? From
{
get
{
return (double?)this.GetValue(EaseMoveAnimation.FromProperty);
}
set
{
this.SetValue(EaseMoveAnimation.FromProperty, value);
}
}
public double? To
{
get
{
return (double?)this.GetValue(EaseMoveAnimation.ToProperty);
}
set
{
this.SetValue(EaseMoveAnimation.ToProperty, value);
}
}
/**//// <summary>
/// 冪指數,值越大,曲線上點的斜率越大,加速度越大,設置為5時效果較好
/// </summary>
public double? Power
{
get
{
return (double?)this.GetValue(EaseMoveAnimation.PowerProperty);
}
set
{
this.SetValue(EaseMoveAnimation.PowerProperty, value);
}
}
protected override double GetCurrentValueCore(double defaultOriginValue, double defaultDestinationValue, AnimationClock animationClock)
{
double from = (this.From==null?defaultDestinationValue:(double)this.From);
double to = (this.To==null?defaultOriginValue:(double)this.To);
double delta = to - from;
double power = this.Power == null ? 2 : (double)this.Power;
//加速
return delta * Math.Pow(animationClock.CurrentProgress.Value, power) + from;
//return delta * Math.Pow(animationClock.CurrentProgress.Value, 1/power) + from;
//先加速後減速
//if (animationClock.CurrentProgress.Value < 0.5)
//{
// return delta / 2 * Math.Pow(animationClock.CurrentProgress.Value * 2, power) + from;
/
本文配套源碼