Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Apress pro Silverlight 3 in C# phần 6 pps
Nội dung xem thử
Mô tả chi tiết
325
CHAPTER 10
■ ■ ■
Animation
Animation allows you to create truly dynamic user interfaces. It’s often used to apply effects–
for example, icons that grow when you move over them, logos that spin, text that scrolls into
view, and so on. Sometimes, these effects seem like excessive glitz. But used properly,
animations can enhance an application in a number of ways. They can make an application
seem more responsive, natural, and intuitive. (For example, a button that slides in when you
click it feels like a real, physical button–not just another gray rectangle.) Animations can also
draw attention to important elements and guide the user through transitions to new content.
(For example, an application could advertise new content with a twinkling, blinking, or pulsing
icon.)
Animations are a core part of the Silverlight model. That means you don’t need to use
timers and event-handling code to put them into action. Instead, you can create and configure
them declaratively, using XAML markup. Animations also integrate themselves seamlessly into
ordinary Silverlight pages. For example, if you animate a button so it drifts around the page, the
button still behaves like a button. It can be styled, it can receive focus, and it can be clicked to
fire off the typical event-handling code.
In this chapter, you’ll consider the set of animation classes that Silverlight provides.
You’ll see how to construct them with XAML and (more commonly) how to control them with
code. Along the way, you’ll see a wide range of animation examples, including page transitions
and a simple catch-the-bombs game.
■ What’s New Silverlight 3 adds a feature called animation easing, which uses mathematical formulas to
create more natural animated effects (see the “Animation Easing” section). Although this is the only truly new
animation feature, you can create a wide range of new animated effects by combining Silverlight animation with
two features you learned about in Chapter 9: perspective projections and pixel shaders. (You’ll see an example
of both in this chapter.) Finally, Silverlight 3 adds hardware acceleration that can increase the performance of
some animations, and is described in the “Hardware Acceleration” section at the end of this chapter.
Understanding Silverlight Animation
Often, an animation is thought of as a series of frames. To perform the animation, these frames
are shown one after the other, like a stop-motion video.
CHAPTER 10 ■ ANIMATION
326
Silverlight animations use a dramatically different model. Essentially, a Silverlight animation
is a way to modify the value of a dependency property over an interval of time. For
example, to make a button that grows and shrinks, you can modify its Width property in an
animation. To make it shimmer, you can change the properties of the LinearGradientBrush that
it uses for its background. The secret to creating the right animation is determining what
properties you need to modify.
If you want to make other changes that can’t be made by modifying a property, you’re
out of luck. For example, you can’t add or remove elements as part of an animation. Similarly,
you can’t ask Silverlight to perform a transition between a starting scene and an ending scene
(although some crafty workarounds can simulate this effect). And finally, you can use
animation only with a dependency property, because only dependency properties use the
dynamic value-resolution system (described in Chapter 4) that takes animations into account.
■ Note Silverlight animation is a scaled-down version of the WPF animation system. It keeps the same
conceptual framework, the same model for defining animations with animation classes, and the same storyboard
system. However, WPF developers will find some key differences, particularly in the way animations are created
and started in code. (For example, Silverlight elements lack the built-in BeginAnimation() method that they have
in WPF.)
GOING BEYOND SILVERLIGHT ANIMATION
At first glance, the property-focused nature of Silverlight animations seems terribly limiting. But
as you work with Silverlight, you’ll find that it’s surprisingly capable. You can create a wide range
of animated effects using common properties that every element supports. In this chapter, you’ll
even see how you can use it to build a simple game.
That said, in some cases the property-based animation system won’t suit. As a rule of
thumb, the property-based animation is a great way to add dynamic effects to an otherwise
ordinary application (like buttons that glow, pictures that expand when you move over them, and
so on). However, if you need to use animations as part of the core purpose of your application,
and you want them to continue running over the lifetime of your application, you may need
something more flexible and more powerful. For example, if you’re creating a complex arcade
game or using physics calculations to model collisions, you’ll need greater control over the
animation.
Later in this chapter, you’ll learn how to take a completely different approach with framebased animations. In a frame-based animation, your code runs several times a second, and each
time it runs you have a chance to modify the content of your window. For more information, see
the section “Frame-Based Animation.”
CHAPTER 10 ■ ANIMATION
327
The Rules of Animation
In order to understand Silverlight animation, you need to be aware of the following key rules:
• Silverlight animations are time-based. You set the initial state, the final state, and the
duration of your animation. Silverlight calculates the frame rate.
• Animations act on properties. A Silverlight animation can do only one thing: modify the
value of a property over an interval of time. This sounds like a significant limitation (and
it many ways, it is), but you can create a surprisingly large range of effects by modifying
properties.
• Every data type requires a different animation class. For example, the Button.Width
property uses the double data type. To animate it, you use the DoubleAnimation class. If
you want to modify the color that’s used to paint the background of a Canvas, you need
to use the ColorAnimation class.
Silverlight has relatively few animation classes, so you’re limited in the data types you
can use. At present, you can use animations to modify properties with the following data types:
double, object, Color, and Point. However, you can also craft your own animation classes that
work for different data types–all you need to do is derive from
System.Windows.Media.Animation and indicate how the value should change as time passes.
Many data types don’t have a corresponding animation class because it wouldn’t be
practical. A prime example is enumerations. For example, you can control how an element is
placed in a layout panel using the HorizontalAlignment property, which takes a value from the
HorizontalAlignment enumeration. But the HorizontalAlignment enumeration allows you to
choose among only four values (Left, Right, Center, and Stretch), which greatly limits its use in
an animation. Although you can swap between one orientation and another, you can’t
smoothly transition an element from one alignment to another. For that reason, there’s no
animation class for the HorizontalAlignment data type. You can build one yourself, but you’re
still constrained by the four values of the enumeration.
Reference types aren’t usually animated. However, their subproperties are. For
example, all content controls sport a Background property that lets you set a Brush object that’s
used to paint the background. It’s rarely efficient to use animation to switch from one brush to
another, but you can use animation to vary the properties of a brush. For example, you can vary
the Color property of a SolidColorBrush (using the ColorAnimation class) or the Offset property
of a GradientStop in a LinearGradientBrush (using the DoubleAnimation class). Doing so
extends the reach of Silverlight animation, allowing you to animate specific aspects of an
element’s appearance.
■ Tip As you’ll see, DoubleAnimation is by far the most useful of Silverlight’s animation classes. Most of the
properties you’ll want to change are doubles, including the position of an element on a Canvas, its size, its
opacity, and the properties of the transforms it uses.
CHAPTER 10 ■ ANIMATION
328
Creating Simple Animations
Creating an animation is a multistep process. You need to create three separate ingredients: an
animation object to perform your animation, a storyboard to manage your animation, and an
event handler (an event trigger) to start your storyboard. In the following sections, you’ll tackle
each of these steps.
The Animation Class
Silverlight includes two types of animation classes. Each type of animation uses a different
strategy for varying a property value:
• Linear interpolation: The property value varies smoothly and continuously over the
duration of the animation. (You can use animation easing to create more complex
patterns of movement that incorporate acceleration and deceleration, as described later
in this chapter.) Silverlight includes three such classes: DoubleAnimation,
PointAnimation, and ColorAnimation.
• Key-frame animation: Values can jump abruptly from one value to another, or they can
combine jumps and periods of linear interpolation (with or without animation easing).
Silverlight includes four such classes: ColorAnimationUsingKeyFrames,
DoubleAnimationUsingKeyFrames, PointAnimationUsingKeyFrames, and
ObjectAnimationUsingKeyFrames.
In this chapter, you’ll begin by focusing on the indispensable DoubleAnimation class,
which uses linear interpolation to change a double from a starting value to its ending value.
Animations are defined using XAML markup. Although the animation classes aren’t
elements, they can be created with the same XAML syntax. For example, here’s the markup
required to create a DoubleAnimation:
<DoubleAnimation From="160" To="300" Duration="0:0:5"></DoubleAnimation>
This animation lasts 5 seconds (as indicated by the Duration property, which takes a
time value in the format Hours:Minutes:Seconds.FractionalSeconds). While the animation is
running, it changes the target value from 160 to 300. Because the DoubleAnimation uses linear
interpolation, this change takes place smoothly and continuously.
There’s one important detail that’s missing from this markup. The animation indicates
how the property will be changed, but it doesn’t indicate what property to use. This detail is
supplied by another ingredient, which is represented by the Storyboard class.
The Storyboard Class
The storyboard manages the timeline of your animation. You can use a storyboard to group
multiple animations, and it also has the ability to control the playback of animation–pausing
it, stopping it, and changing its position. But the most basic feature provided by the Storyboard
class is its ability to point to a specific property and specific element using the TargetProperty
and TargetName properties. In other words, the storyboard bridges the gap between your
animation and the property you want to animate.
CHAPTER 10 ■ ANIMATION
329
Here’s how you can define a storyboard that applies a DoubleAnimation to the Width
property of a button named cmdGrow:
<Storyboard x:Name="storyboard"
Storyboard.TargetName="cmdGrow" Storyboard.TargetProperty="Width">
<DoubleAnimation From="160" To="300" Duration="0:0:5"></DoubleAnimation>
</Storyboard>
The Storyboard.TargetProperty property identifies the property you want to change.
(In this example, it’s Width.) If you don’t supply a class name, the storyboard uses the parent
element. If you want to set an attached property (for example, Canvas.Left or Canvas.Top), you
need to wrap the entire property in brackets, like this:
<Storyboard x:Name="storyboard"
Storyboard.TargetName="cmdGrow" Storyboard.TargetProperty="(Canvas.Left)">
...
</Storyboard>
Both TargetName and TargetProperty are attached properties. That means you can
apply them directly to the animation, as shown here:
<Storyboard x:Name="storyboard">
<DoubleAnimation
Storyboard.TargetName="cmdGrow" Storyboard.TargetProperty="Width"
From="160" To="300" Duration="0:0:5"></DoubleAnimation>
</Storyboard>
This syntax is more common, because it allows you to put several animations in the
same storyboard but set each animation to act on a different element and property. Although
you can’t animate the same property at the same time with multiple animations, you can (and
often will) animate different properties of the same element at once.
Starting an Animation with an Event Trigger
Defining a storyboard and an animation are the first steps to creating an animation. To actually
put this storyboard into action, you need an event trigger. An event trigger responds to an event
by performing a storyboard action. The only storyboard action that Silverlight currently
supports is BeginStoryboard, which starts a storyboard (and hence all the animations it
contains).
The following example uses the Triggers collection of a page to attach an animation to
the Loaded event. When the Silverlight content is first rendered in the browser, and the page
element is loaded, the button begins to grow. Five seconds later, its width has stretched from
160 pixels to 300.
<UserControl ... >
<UserControl.Triggers>
<EventTrigger>
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="cmdGrow"
Storyboard.TargetProperty="Width"