Document directory
- A simplest WPF Animation
- Animation type
- Animation is a timeline
- Storyboards
- A simple Key Frame Animation
- Key Frame Animation types
- Key Frame and key time
- Key Frame Type
- Interpolation Method
For windowsform programmers, there is no animation concept. If we want to achieve a dynamic effect, we need to configure a timer and then call the callback function cyclically according to the timer frequency for a period of time.
Constantly update the attributes of the target function to achieve the animation effect.
Simulate animation with a timer
Place a circle on the Interface
<Canvas> <Ellipse Canvas.Left="24" Canvas.Top="68" Margin="39,39,0,0" Stroke="Black" Height="38" HorizontalAlignment="Left"
Verticalalignment = "TOP" width = "42" fill = "yellow" name = "Yuan"/> <button canvas. left = "38" canvas. top = "213" Height = "23" name = "button1" width = "75" Click = "button#click"> Start </button> </canvas>
When the button is clicked, a timer is created for execution.
DispatcherTimer timer; int i = 0;
private void button1_Click(object sender, RoutedEventArgs e) { timer = new DispatcherTimer(DispatcherPriority.Normal); timer.Tick += new EventHandler(timer_Tick); timer.Interval = TimeSpan.FromMilliseconds(20); timer.Start(); }
The timer object is in the namespace of system. Windows. threading.
Void timer_tick (Object sender, eventargs e) {// throw new notimplementedexception (); move (new point (0, 1);} public void move (point P) {// here we want the circle to move Ppoint point Pt = new point (canvas. gettop (yuan), canvas. getleft (yuan); // obtain the position of the current object // change the position canvas. settop (Yuan, PT. X + P. x); canvas. setleft (Yuan, PT. Y + P. y); I ++; if (I> = 100) {timer. stop ();}}
Here we move the circle object to the right and stop it after 100 executions. In this way, a timer-based animation is simulated.
You can also use
System. Timers. Timer
System.Timers.Timer tm = new System.Timers.Timer(); tm.Interval = 20; tm.Elapsed += new System.Timers.ElapsedEventHandler(tm_Elapsed); tm.Start();
Or system. Threading. timer,
System. Threading. Timer is a simple lightweight timer that uses the callback method and is provided by the thread pool thread. It is not recommended to use Windows Forms because the callback is not performed on the user interface thread. System. Windows. Forms. Timer is a better choice for Windows Forms. To obtain the server-based timer function, consider using system. Timers. Timer, which can trigger events and have other functions. 【Msdn]
Windows programmers may be familiar with this implementation method, but it is not recommended to use a timer to implement animation. The timer cannot be synchronized Based on the display's vertical update rate,
It cannot be synchronized with the rendering engine of WPF.[WPF Secrets]
Frame-based animation using rendering events
In WPF, you can use the rendering event of system. Windows. Media. compositiontarget to implement frame-based animation. What is different from timer is
It is not triggered in the Custom time interval, but once after the layout and before the rendering.
CompositiontargetIs a class that indicates that you are drawing a display drawing of your application. [Msdn]
CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering); void CompositionTarget_Rendering(object sender, EventArgs e) { //throw new NotImplementedException(); move(new Point(0, 1)); }
Public void move (point P) {// here we want the circle to move Ppoint point Pt = new point (canvas. gettop (yuan), canvas. getleft (yuan); // obtain the position of the current object // change the position canvas. settop (Yuan, PT. X + P. x); canvas. setleft (Yuan, PT. Y + P. Y );}
Since the rendering event is related to the page refreshing frequency, we cannot control its execution. However, the handler is called in the UI thread, so there is no need to worry about thread communication.
WPF Animation
Although the above two methods are also a way to implement animation, the animation class is provided in WPF to make the animation a simpler and more descriptive process. In
The system. Windows. Media. animation namespace defines many classes to easily describe animations.
To implement an animation in WPF requires three necessary conditions: animation objects, storyboards, and event triggers.
A simplest WPF Animation
Write the following code under a button:
// 1. create an animation object doubleanimation = new doubleanimation (); doubleanimation. from = 10; // set the start value to doubleanimation. to = 100; // set the end value doubleanimation. duration = new duration (timespan. fromseconds (5); // animation running time doubleanimation. autoreverse = true; // sets the playback of doubleanimation in reverse mode after the animation is played. repeatbehavior = repeatbehavior. forever; // set to loop playback // 2. create a storyboard and add the animation object to it. storyboard = new storyboard (); storyboa Rd. Children. Add (doubleanimation); // 3. Specify the storyboard. settarget (doubleanimation, Yuan) object to execute the storyboard; // specify the object to execute the animation. // 4. Specify the storyboard. settargetproperty (doubleanimation, new propertypath ("(canvas. Top)"); storyboard. Begin (); // start the animation
A doubleanimation animation is defined above, and the animation is added to the storyboard. Finally, the animation objects and changed attributes are set.
Of course, storyboard also provides the stop, pause, and resume methods to control the animation.
Animation type
There are two types of Animation: from/to/by and key frame animation.
From/to/by Animation: the animation is processed between the start value from and the end value to. The time between the animations is controlled by the Duration Attribute, to specify the end value relative to the start value, set the by attribute
Key Frame Animation: Play an animation between a series of values specified by the key frame object.
Attribute type |
Corresponding BASIC (from/to/by) Animation |
Corresponding Key Frame Animation |
Color |
Coloranimation |
Coloranimationusingkeyframes |
Double |
Doubleanimation |
Doubleanimationusingkeyframes |
Point |
Pointanimation |
Pointanimationusingkeyframes |
Object |
None |
Objectanimationusingkeyframes |
Coloranimation uses linear interpolation within a specified duration to animation the color attribute values between two target values.
Doubleanimation uses linear interpolation within a specified duration to animation the double attribute values between two target values.
Pointanimation uses linear interpolation within a specified duration to animation the point attribute values between two target values.
Animation is a timeline
All animations are inherited from timeline objects, so all animations are dedicated time series. Common attributes include:
Duration indicates that the timeline is repeated once.
Autoreverse specifies whether the timeline regresses after it reaches the end of its duration. If you set this animation property to true
Repeatbehavior specifies the number of times the timeline is played.
Begintime: Specifies the animation start time.
Speedratio: Set the animation speed
Fillbehavior sets the action after the animation ends. Two values hold the current value while the stop value changes to the initial value.
Storyboards
The storyboard object provides a series of APIs to control the playback of objects. Start, pause, continue, stop, and so on.
The storyboard provides additional attributes for targetname and targetproperty by setting these attributes on the animation. It tells us that the animation processes those content.
// 3. Specify the storyboard. settarget (doubleanimation, Yuan) object to execute the storyboard; // specify the object to execute the animation. // 4. Specify the storyboard. settargetproperty (doubleanimation, new propertypath ("(canvas. Top)") for animation processing )"));
In the example, Steps 3 and 4 are used to set these two values.
In WPF, you can easily create animations. In the above three ways to create animations, you can create deep blue series tutorials in the garden.C # develop WPF/Silverlight animations and game series tutorials (game tutorial)
The three types of animations are also described in detail, and I started to look at WPF and started to see the deep blue tutorial. Three animation methods are introduced in the book "WPF secrets. This is the third type.
Key Frame Animation
The Key Frame Animation is similar to the from/to/by animation. The Key Frame Animation displays the value of the Target attribute in the form of an animation. It creates a transition between its targets through its duration.
However, the from/to/by animation creates a transition between two values, while the karaoke Key Frame Animation can create a transition between any number of target values.
Key Frame Animation needs to create a key frame object and add it to the animationKeyframesAttribute. The animation is running. It will transition between specified frames.
A simple Key Frame Animation
<Canvas> <ellipse canvas. left = "38" canvas. top = "40" Height = "49" name = "ellipse1" stroke = "black" width = "52" fill = "Turquoise"/> <button canvas. left = "92" canvas. top = "233" Height = "23" name = "button1" width = "75" Click = "button#click"> Start </button>
</Canvas>
Place a circle and a button on the Interface
Click the event button to write
// 1. Create a storyboard = new storyboard (); // 2. Create a Key Frame Animation
Doubleanimationusingkeyframes = new doubleanimationusingkeyframes (); storyboard. children. add (doubleanimationusingkeyframes); // Add the animation to the storyboard. settarget (doubleanimationusingkeyframes, ellipse1); // you can specify targetstoryboard. settargetproperty (doubleanimationusingkeyframes, new propertypath ("(canvas. top) "); // sets targetpropertydoubleanimationusingkeyframes. duration = new duration (timespan. fromseconds (10); // 3. create a key frame and add it to keyframes. Here three spline key frames lineardoublekeyframe = new lineardoublekeyframe (200, keytime. fromtimespan (timespan. fromseconds (2); doubleanimationusingkeyframes. keyframes. add (lineardoublekeyframe );
doubleAnimationUsingKeyFrames .KeyFrames .Add (new DiscreteDoubleKeyFrame(300,KeyTime.FromTimeSpan(TimeSpan.FromSeconds(5))));doubleAnimationUsingKeyFrames .KeyFrames .Add (new SplineDoubleKeyFrame(600,KeyTime.FromTimeSpan(TimeSpan.FromSeconds(10)),
new KeySpline (new Point (0,1),new Point (1,0)))); storyboard.Begin();
In this Key Frame Animation, we made linear interpolation of object values from 0 to 200 in the first two seconds, discrete Interpolation of object values from 200 to 300 in 2 to 5 seconds, and Spline Interpolation of object values from 300 to 600 in 5 to 10 seconds.
The value of the object here, that is, the value of canvas. Top of ellipse1.
Key Frame Animation types
Attribute type |
Corresponding Key Frame Animation class |
Supported interpolation methods |
Color |
Coloranimationusingkeyframes |
Discrete, linear, and Spline |
Double |
Doubleanimationusingkeyframes |
Discrete, linear, and Spline |
Point |
Pointanimationusingkeyframes |
Discrete, linear, and Spline |
Object |
Objectanimationusingkeyframes |
Discrete |
Compared with the from/to/by animation, an object-type animation is added.
Key Frame and key time
The key frame is mainly used to specify the keytime and the target value. Each key frame provides these two attributes.
ValueAttribute specifies the target value of the Key Frame
KeytimeThe attribute specifies the time when the value of the key frame is reached. This time is within the duration period.
After a key frame starts, the key frame is cyclically located according to the sequence defined by the keytime attribute. If no key frame exists on 0, the animation creates a transition between the current value of the Target attribute and the value of the first frame.
The animation uses the interpolation method specified by the second frame to create a transition between the value of the first and second key frames. The transition starts from the keytime of the first frame, and the animation of the keytime of the second frame continues, and the transition between each subsequent key frame and the previous key frame is created.
Finally, the animation transitions to the Key Frame value with the maximum key time (equal to or less than the animation's duration.
Key Frame Type
Key Frame types include discrete, linear, and Spline (discrete, linear, and Spline)
The key frame types follow the naming conventions below:
_ Interpolationmethod_typekeyframe
Here, _ interpolationmethod is the interpolation method (discrete, linear, and Spline) used by the key frame, and _ type is the type of the value (double, color, point, object ). Here, objects only support discrete interpolation methods.
For example, you can use the following three key frame types with doubleanimationusingkeyframes: discretedoublekeyframe, lineardoublekeyframe, and splinedoublekeyframe.
Interpolation Method
Linear (linear interpolation): linear interpolation should be the best method to understand. An animation will be played at a fixed speed for a period of time. The relationship between time and value is a linear relationship.
Discrete (discrete interpolation): using discrete interpolation, animation functions will jump from one value to the next value without interpolation. Its value is a skip value.
Spline (spline interpolation): using spline interpolation can be used to achieve a more realistic timing effect. When specifying the value and keytime, you can also specify the keyspline and use two control points to specify the three-power besell curve of the Key Frame progress. Of course, spline interpolation is hard to understand. For example: