2009 pearson education, inc. all rights reserved. 1 17 wpf graphics and multimedia
TRANSCRIPT
2009 Pearson Education, Inc. All rights reserved.
1
1717
WPF Graphicsand Multimedia
2009 Pearson Education, Inc. All rights reserved.
2
Nowadays people's visual imagination is so much more sophisticated, so much more developed, particularly in young people, that now you can make an image which just slightly suggests something, they can make of it what they will.
– Robert Doisneau
In shape, it is perfectly elliptical. In texture, it is smooth and lustrous. In color, it ranges from pale alabaster to warm terra cotta.
– Sydney J Harris, “Tribute to an Egg”
2009 Pearson Education, Inc. All rights reserved.
3
There are painters who transform the sun into a yellow spot, but there are others who, thanks to their art and intelligence, transform a yellow spot into the sun.
– Pablo Picasso
2009 Pearson Education, Inc. All rights reserved.
4
OBJECTIVES
In this chapter you will learn: To manipulate fonts. To draw basic shapes like Lines, Rectangles, Ellipses and Polygons.
To use brushes to customize the Fill or Background of a GUI object.
To use transforms to reposition or reorient GUI elements.
To completely customize the look of a controlwhile maintaining its functionality.
To animate the properties of a GUI element. To transform and animate 3-D objects.
2009 Pearson Education, Inc. All rights reserved.
5
17.1 Introduction
17.2 Controlling Fonts
17.3 Basic Shapes
17.4 Polygons and Polylines
17.5 Brushes
17.6 Transforms
17.7 WPF Customization: A Television GUI
17.8 Animations
17.9 (Optional) 3-D Objects and Transforms
2009 Pearson Education, Inc. All rights reserved.
6
17.1 Introduction
• The graphics system in WPF is designed to use your computer’s graphics hardware to reduce the load on the CPU and speed up graphics rendering.
• WPF graphics are measured in resolution-independent pixels, where one pixel typically represents 1/96 of an inch.
• WPF graphics are rendered on screen using a vector-based system, allowing graphic elements to be preserved across any rendering size.
• Raster-based systems have the precise pixels specified for each graphical element. Raster-based graphics tend to degrade in appearance as they are scaled larger.
• WPF also includes 3-D modeling and rendering capabilities.
2009 Pearson Education, Inc. All rights reserved.
7
1 <!-- Fig. 17.1: UsingFonts.xaml -->
2 <!-- Formatting fonts in XAML code. -->
3 <Window x:Class="UsingFonts.UsingFontsWindow"
4 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
5 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
6 Title="UsingFonts" Height="120" Width="400">
7
8 <StackPanel>
9 <!-- make a font bold using the FontWeight -->
10 <TextBlock FontFamily="Arial" FontSize="12" FontWeight="Bold">
11 Arial 12 point bold.</TextBlock>
12
13 <!-- if no font size is specified, default size is used -->
14 <TextBlock FontFamily="Times New Roman">
15 Times New Roman plain, default size.</TextBlock>
16
Outline
UsingFonts.xaml
( 1 of 3 )
• Figure 17.1 shows how to use TextBlocks and control the appearance of the displayed text.
Defining the appearance of the font.
Fig. 17.1 | Formatting fonts in XAML code. (Part 1 of 3.)
2009 Pearson Education, Inc. All rights reserved.
8
17 <!-- specifying a different font size and using FontStyle -->
18 <TextBlock FontFamily="Courier New" FontSize="16"
19 FontStyle="Italic" FontWeight="Bold">
20 Courier New 16 point bold and italic.
21 </TextBlock>
22
23 <!-- using Overline and Baseline TextDecorations -->
24 <TextBlock>
25 <TextBlock.TextDecorations>
26 <TextDecoration Location="OverLine" />
27 <TextDecoration Location="Baseline" />
28 </TextBlock.TextDecorations>
29 Default font with overline and baseline.
30 </TextBlock>
31
Outline
Applying an italic style.
UsingFonts.xaml
( 2 of 3 )
TextDecorations draw a horizontal line through the text.
Fig. 17.1 | Formatting fonts in XAML code. (Part 2 of 3.)
2009 Pearson Education, Inc. All rights reserved.
9
32 <!-- using Strikethrough and Underline TextDecorations -->
33 <TextBlock>
34 <TextBlock.TextDecorations>
35 <TextDecoration Location="Strikethrough" />
36 <TextDecoration Location="Underline" />
37 </TextBlock.TextDecorations>
38 Default font with strikethrough and underline.
39 </TextBlock>
40 </StackPanel>
41 </Window>
Outline
Fig. 17.1 | Formatting fonts in XAML code. (Part 3 of 3.)
TextDecorations draw a horizontal line through the text.
UsingFonts.xaml
( 3 of 3 )
2009 Pearson Education, Inc. All rights reserved.
10
17.2 Controlling Fonts (Cont.)
• The FontFamily property defines the font.
• The FontSize property defines the text size in points (default 12).
• The FontWeight and FontStyle properties change text appearance.
2009 Pearson Education, Inc. All rights reserved.
11
17.2 Controlling Fonts (Cont.)
• TextDecorations draw a horizontal line through the text.
– Overline and Baseline create lines above the text and at the base of the text.
– Strikethrough and Underline create lines through the middle of the text and under the text.
2009 Pearson Education, Inc. All rights reserved.
12
1 <!-- Fig. 17.2: BasicShapes.xaml -->
2 <!-- Drawing basic shapes in XAML. -->
3 <Window x:Class="BasicShapes.BasicShapesWindow"
4 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
5 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
6 Title="BasicShapes" Height="200" Width="500">
7 <Canvas>
8 <!-- Rectangle with fill but no stroke -->
9 <Rectangle Canvas.Left="90" Canvas.Top="30" Width="150" Height="90"
10 Fill="Blue" />
11
12 <!-- Lines defined by starting points and ending points-->
13 <Line X1="90" Y1="30" X2="110" Y2="40" Stroke="Black" />
14 <Line X1="90" Y1="120" X2="110" Y2="130" Stroke="Black" />
15 <Line X1="240" Y1="30" X2="260" Y2="40" Stroke="Black" />
16 <Line X1="240" Y1="120" X2="260" Y2="130" Stroke="Black" />
17
18 <!-- Rectangle with stroke but no fill -->
19 <Rectangle Canvas.Left="110" Canvas.Top="40" Width="150"
20 Height="90" Stroke="Black" />
Outline• The BasicShapes example (Fig. 17.2) shows you how
to display Lines, Rectangles and Ellipses. BasicShapes.xaml
( 1 of 2 )
A Canvas uses coordinates to position the shapes.
A Line is defined by its two endpoints—X1, Y1 and X2, Y2.
Fig. 17.2 | Drawing basic shapes in XAML. (Part 1 of 2.)
2009 Pearson Education, Inc. All rights reserved.
13
21
22 <!-- Ellipse with fill and no stroke -->
23 <Ellipse Canvas.Left="280" Canvas.Top="75" Width="100" Height="50"
24 Fill="Red" />
25 <Line X1="380" Y1="55" X2="380" Y2="100" Stroke="Black" />
26 <Line X1="280" Y1="55" X2="280" Y2="100" Stroke="Black" />
27
28 <!-- Ellipse with stroke and no fill -->
29 <Ellipse Canvas.Left="280" Canvas.Top="30" Width="100" Height="50"
30 Stroke="Black" />
31 </Canvas>
32 </Window>
Outline
Defining an Ellipse.
Fig. 17.2 | Drawing basic shapes in XAML. (Part 2 of 2.)
BasicShapes.xaml
( 1 of 2 )
2009 Pearson Education, Inc. All rights reserved.
14
17.3 Basic Shapes (Cont.)
• A Canvas uses coordinates to position the shapes.
• A Rectangle’s color is set in its Fill property, which can be any Color or Brush.
• A Rectangle’s Stroke property defines the color of the outline of the shape.
• A Line is defined by its two endpoints—X1, Y1 and X2, Y2.
2009 Pearson Education, Inc. All rights reserved.
15
Outline
DrawPolygons.xaml
( 1 of 4 )• A Polyline draws a series of connected lines
defined by a set of points.
• A Polygon does the same but connects the start and end points to make a closed figure.
• The application DrawPolygons (Fig. 17.3) allows you to click anywhere on the Canvas to define points for one of three shapes.
• A Filled Polygon has a Fill property specified while a Polygon does not.
2009 Pearson Education, Inc. All rights reserved.
16
1 <!-- Fig. 17.3: DrawPolygons.xaml -->
2 <!-- Defining Polylines and Polygons in XAML. -->
3 <Window x:Class="DrawPolygons.DrawPolygonsWindow"
4 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
5 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
6 Title="DrawPolygons" Height="400" Width="450" Name="mainWindow">
7 <Grid>
8 <Grid.ColumnDefinitions>
9 <ColumnDefinition />
10 <ColumnDefinition Width="Auto" />
11 </Grid.ColumnDefinitions>
12
13 <!-- Canvas contains two polygons and a polyline -->
14 <!-- only the shape selected by the radio button is visible -->
15 <Canvas Name="drawCanvas" Grid.Column="0" Background="White"
16 MouseDown="drawCanvas_MouseDown">
17 <Polyline Name="polyLine" Stroke="Black"
18 Visibility="Collapsed" />
19 <Polygon Name="polygon" Stroke="Black" Visibility="Collapsed" />
20 <Polygon Name="filledPolygon" Fill="DarkBlue"
21 Visibility="Collapsed" />
22 </Canvas>
Outline
DrawPolygons.xaml
( 2 of 4 )
Defining a two-column GUI.
Nested in the Canvas are the Polyline and two Polygons.
Fig. 17.3 | Defining Polylines and Polygons in XAML. (Part 1 of 3.)
2009 Pearson Education, Inc. All rights reserved.
17
23
24 <!-- StackPanel containing the RadioButton options -->
25 <StackPanel Grid.Column="1" Orientation="Vertical"
26 Background="WhiteSmoke">
27 <GroupBox Header="Select Type" Margin="10">
28 <StackPanel>
29 <!-- Polyline option -->
30 <RadioButton Name="lineRadio" Margin="5"
31 Checked="lineRadio_Checked">Polyline</RadioButton>
32
33 <!-- unfilled Polygon option -->
34 <RadioButton Name="polygonRadio" Margin="5"
35 Checked="polygonRadio_Checked">Polygon</RadioButton>
36
37 <!-- filled Polygon option -->
38 <RadioButton Name="filledPolygonRadio" Margin="5"
39 Checked="filledPolygonRadio_Checked">
40 Filled Polygon</RadioButton>
41 </StackPanel>
42 </GroupBox>
Outline
DrawPolygons.xaml
( 3 of 4 )
RadioButtons allow you to select which shape appears in the Canvas.
Fig. 17.3 | Defining Polylines and Polygons in XAML. (Part 2 of 3.)
2009 Pearson Education, Inc. All rights reserved.
18
43
44 <!-- Button clears the shape from the canvas -->
45 <Button Name="clearButton" Click="clearButton_Click"
46 Margin="5">Clear</Button>
47 </StackPanel>
48 </Grid>
49 </Window>
Outline
DrawPolygons.xaml
( 4 of 4 )
a) Application with the Polyline option selected. b) Application with the Filled Polygon option selected.
Fig. 17.3 | Defining Polylines and Polygons in XAML. (Part 3 of 3.)
A Button clears the shape’s points to allow you start over.
2009 Pearson Education, Inc. All rights reserved.
19
17.4 Polygons and Polylines (Cont.)
• The Visibility of a GUI element can be set to Visible, Collapsed or Hidden.
– A Hidden object occupies space in the GUI but is not visible.
– A Collapsed object has a Width and Height of 0.
2009 Pearson Education, Inc. All rights reserved.
20
1 // Fig. 17.4: DrawPolygons.xaml.cs
2 // Drawing Polylines and Polygons.
3 using System.Windows;
4 using System.Windows.Input;
5 using System.Windows.Media;
6
7 namespace DrawPolygons
8 {
9 public partial class DrawPolygonsWindow : Window
10 {
11 // stores the collection of points for the multisided shapes
12 private PointCollection points = new PointCollection();
13
14 // initialize the points of the shapes
15 public DrawPolygonsWindow()
16 {
17 InitializeComponent();
18
19 polyLine.Points = points; // assign Polyline points
20 polygon.Points = points; // assign Polygon points
21 filledPolygon.Points = points; // assign filled Polygon points
22 } // end constructor
Outline
DrawPolygons.xaml.cs
( 1 of 4 )
• The code-behind file for the application is shown in Fig. 17.4.
A Point Collection stores Point objects.
We set each shape’s Points property to reference the PointCollection.
Fig. 17.4 | Drawing Polylines and Polygons. (Part 1 of 4.)
2009 Pearson Education, Inc. All rights reserved.
21
23
24 // adds a new point when the user clicks on the canvas
25 private void drawCanvas_MouseDown( object sender,
26 MouseButtonEventArgs e )
27 {
28 // add point to collection
29 points.Add( e.GetPosition( drawCanvas ) );
30 } // end method drawCanvas_MouseDown
31
32 // when the clear Button is clicked
33 private void clearButton_Click( object sender, RoutedEventArgs e )
34 {
35 points.Clear(); // clear the points from the collection
36 } // end method clearButton_Click
37
Outline
DrawPolygons.xaml.cs
( 2 of 4 )
The collection’s Add method adds new points to the end of the collection.
The Clear method of points erases its elements.
Fig. 17.4 | Drawing Polylines and Polygons. (Part 2 of 4.)
2009 Pearson Education, Inc. All rights reserved.
22
38 // when the user selects the Polyline
39 private void lineRadio_Checked( object sender, RoutedEventArgs e )
40 {
41 // Polyline is visible, the other two are not
42 polyLine.Visibility = Visibility.Visible;
43 polygon.Visibility = Visibility.Collapsed;
44 filledPolygon.Visibility = Visibility.Collapsed;
45 } // end method lineRadio_Checked
46
47 // when the user selects the Polygon
48 private void polygonRadio_Checked( object sender,
49 RoutedEventArgs e )
50 {
51 // Polygon is visible, the other two are not
52 polyLine.Visibility = Visibility.Collapsed;
53 polygon.Visibility = Visibility.Visible;
54 filledPolygon.Visibility = Visibility.Collapsed;
55 } // end method polygonRadio_Checked
Outline
DrawPolygons.xaml.cs
( 3 of 4 )
Each RadioButton makes the corresponding shape Visible and sets the other two to Collapsed.
Each RadioButton makes the corresponding shape Visible and sets the other two to Collapsed.
Fig. 17.4 | Drawing Polylines and Polygons. (Part 3 of 4.)
2009 Pearson Education, Inc. All rights reserved.
23
56
57 // when the user selects the filled Polygon
58 private void filledPolygonRadio_Checked( object sender,
59 RoutedEventArgs e )
60 {
61 // filled Polygon is visible, the other two are not
62 polyLine.Visibility = Visibility.Collapsed;
63 polygon.Visibility = Visibility.Collapsed;
64 filledPolygon.Visibility = Visibility.Visible;
65 } // end method filledPolygonRadio_Checked
66 } // end class DrawPolygonsWindow
67 } // end namespace DrawPolygons
Outline
DrawPolygons.xaml.cs
( 4 of 4 )
Each RadioButton makes the corresponding shape Visible and sets the other two to Collapsed.
Fig. 17.4 | Drawing Polylines and Polygons. (Part 4 of 4.)
2009 Pearson Education, Inc. All rights reserved.
24
1 <!-- Fig. 17.5: UsingBrushes.xaml -->
2 <!-- Applying brushes to various XAML elements. -->
3 <Window x:Class="UsingBrushes.UsingBrushesWindow"
4 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
5 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
6 Title="UsingBrushes" Height="450" Width="700">
7 <Grid>
8 <Grid.RowDefinitions>
9 <RowDefinition />
10 <RowDefinition />
11 <RowDefinition />
12 </Grid.RowDefinitions>
13
14 <Grid.ColumnDefinitions>
15 <ColumnDefinition />
16 <ColumnDefinition />
17 </Grid.ColumnDefinitions>
18
Outline
UsingBrushes.xaml
( 1 of 5 )
• Brushes change an element’s graphic properties, such as the Fill, Stroke or Background.
• Run the UsingBrushes application (Fig. 17.5) to see Brushes applied to TextBlocks and Ellipses.
Fig. 17.5 | Applying brushes to various XAML elements. (Part 1 of 5.)
2009 Pearson Education, Inc. All rights reserved.
25
19 <!-- TextBlock with a SolidColorBrush -->
20 <TextBlock FontSize="100" FontWeight="999">
21 <TextBlock.Foreground>
22 <SolidColorBrush Color="#5F2CAE" />
23 </TextBlock.Foreground>
24 Color
25 </TextBlock>
26
27 <!-- Ellipse with a SolidColorBrush (just a Fill) -->
28 <Ellipse Grid.Column="1" Height="100" Width="300" Fill="#5F2CAE" />
29
30 <!-- TextBlock with an ImageBrush -->
31 <TextBlock Grid.Row="1" FontSize="100" FontWeight="999">
32 <TextBlock.Foreground>
33 <!-- Flower image as an ImageBrush -->
34 <ImageBrush ImageSource="flowers.jpg" />
35 </TextBlock.Foreground>
36 Image
37 </TextBlock>
38
Outline
UsingBrushes.xaml
( 2 of 5 )
Using an image to color text.
An ImageBrush paints an image into the property it is assigned to.
Fig. 17.5 | Applying brushes to various XAML elements. (Part 2 of 5.)
2009 Pearson Education, Inc. All rights reserved.
26
39 <!-- Ellipse with an ImageBrush -->
40 <Ellipse Grid.Row="1" Grid.Column="1" Height="100" Width="300">
41 <Ellipse.Fill>
42 <ImageBrush ImageSource="flowers.jpg" />
43 </Ellipse.Fill>
44 </Ellipse>
45
46 <!-- TextBlock with a MediaElement as a VisualBrush -->
47 <TextBlock Grid.Row="2" FontSize="100" FontWeight="999">
48 <TextBlock.Foreground>
49 <!-- VisualBrush with an embedded MediaElement-->
50 <VisualBrush>
51 <VisualBrush.Visual>
52 <MediaElement Source="nasa.wmv" />
53 </VisualBrush.Visual>
54 </VisualBrush>
55 </TextBlock.Foreground>
56 Video
57 </TextBlock>
Outline
UsingBrushes.xaml
( 3 of 5 )
Displaying an image inside of an Ellipse.
Defining a Brush with a video to display as the text appearance.
Fig. 17.5 | Applying brushes to various XAML elements. (Part 3 of 5.)
2009 Pearson Education, Inc. All rights reserved.
27
58
59 <!-- Ellipse with a MediaElement as a VisualBrush -->
60 <Ellipse Grid.Row="2" Grid.Column="1" Height="100" Width="300">
61 <Ellipse.Fill>
62 <VisualBrush>
63 <VisualBrush.Visual>
64 <MediaElement Source="nasa.wmv" />
65 </VisualBrush.Visual>
66 </VisualBrush>
67 </Ellipse.Fill>
68 </Ellipse>
69 </Grid>
70 </Window>
Outline
UsingBrushes.xaml
( 4 of 5 )
Displaying a video inside of an Ellipse.
Fig. 17.5 | Applying brushes to various XAML elements. (Part 4 of 5.)
2009 Pearson Education, Inc. All rights reserved.
28
Outline
UsingBrushes.xaml
( 5 of 5 )
a)
b) c)
Fig. 17.5 | Applying brushes to various XAML elements. (Part 5 of 5.)
2009 Pearson Education, Inc. All rights reserved.
29
17.5 Brushes (Cont.)
• An ImageBrush paints an image into the property it is assigned to.
– To fill text, we assign the ImageBrush to the Foreground property of a TextBlock.
– The Background property specifies the fill for the area surrounding the text.
• The ImageSource is set to the file we want to display (the image file must be added to the project).
2009 Pearson Education, Inc. All rights reserved.
30
17.5 Brushes (Cont.)
• A VisualBrush can paint a video into the property it is assigned to.
• To use audio or video in a WPF application, use a MediaElement object.
• Add the video file to your project by selecting the Add Existing Item... option in the Project menu.
• Select the video in the Solution Explorer. In the Properties window, change the Copy to Output Directory property to Copy if newer.
• You can now set the Source property of your MediaElement to the video.
2009 Pearson Education, Inc. All rights reserved.
31
1 <!-- Fig. 17.6: UsingGradients.xaml -->
2 <!-- Defining gradients in XAML. -->
3 <Window x:Class="UsingGradients.UsingGradientsWindow"
4 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
5 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
6 Title="UsingGradients" Height="200" Width="450">
7 <Grid>
8 <Grid.RowDefinitions>
9 <RowDefinition />
10 <RowDefinition Height="Auto" />
11 <RowDefinition Height="Auto" />
12 <RowDefinition Height="Auto" />
13 </Grid.RowDefinitions>
14
15 <!-- TextBlock in the background to show transparency -->
16 <TextBlock FontSize="30" HorizontalAlignment="Center"
17 VerticalAlignment="Center">Transparency test</TextBlock>
18
Outline
UsingGradients.xaml
( 1 of 4 )
• The UsingGradients example applies a LinearGradientBrush to a Rectangle’s Fill.
• The XAML code for this application is shown in Fig. 17.6.
Fig. 17.6 | Defining gradients in XAML. (Part 1 of 4.)
2009 Pearson Education, Inc. All rights reserved.
32
19 <!-- sample rectangle with linear gradient fill -->
20 <Rectangle>
21 <Rectangle.Fill>
22 <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
23 <!-- gradient stop can define a color at any offset -->
24 <GradientStop x:Name="startGradient" Offset="0.0"
25 Color="White" />
26 <GradientStop x:Name="stopGradient" Offset="1.0"
27 Color="Black" />
28 </LinearGradientBrush>
29 </Rectangle.Fill>
30 </Rectangle>
31
32 <!-- shows which TextBox corresponds with which ARGB value-->
33 <StackPanel Grid.Row="1" Orientation="Horizontal">
34 <TextBlock Width="75" Margin="5">Alpha:</TextBlock>
35 <TextBlock Width="75" Margin="5">Red:</TextBlock>
36 <TextBlock Width="75" Margin="5">Green:</TextBlock>
37 <TextBlock Width="75" Margin="5">Blue:</TextBlock>
38 </StackPanel>
39
Outline
UsingGradients.xaml
( 2 of 4 )
A LinearGradientBrush transitions along a straight path.
A GradientStop defines a single color along the gradient.
Fig. 17.6 | Defining gradients in XAML. (Part 2 of 4.)
2009 Pearson Education, Inc. All rights reserved.
33
40 <!-- GUI to select the color of the first GradientStop -->
41 <StackPanel Grid.Row="2" Orientation="Horizontal">
42 <TextBox Name="fromAlpha" Width="75" Margin="5">255</TextBox>
43 <TextBox Name="fromRed" Width="75" Margin="5">255</TextBox>
44 <TextBox Name="fromGreen" Width="75" Margin="5">255</TextBox>
45 <TextBox Name="fromBlue" Width="75" Margin="5">255</TextBox>
46 <Button Name="fromButton" Width="75" Margin="5"
47 Click="fromButton_Click">Start Color</Button>
48 </StackPanel>
49
50 <!-- GUI to select the color of second GradientStop -->
51 <StackPanel Grid.Row="3" Orientation="Horizontal">
52 <TextBox Name="toAlpha" Width="75" Margin="5">255</TextBox>
53 <TextBox Name="toRed" Width="75" Margin="5">0</TextBox>
54 <TextBox Name="toGreen" Width="75" Margin="5">0</TextBox>
55 <TextBox Name="toBlue" Width="75" Margin="5">0</TextBox>
56 <Button Name="toButton" Width="75" Margin="5"
57 Click="toButton_Click">End Color</Button>
58 </StackPanel>
59 </Grid>
60 </Window>
Outline
UsingGradients.xaml
( 3 of 4 )
Fig. 17.6 | Defining gradients in XAML. (Part 3 of 4.)
2009 Pearson Education, Inc. All rights reserved.
34
Outlinea) The application immediately after it is loaded.
b) The application after changing the start and end colors.
Fig. 17.6 | Defining gradients in XAML. (Part 4 of 4.)
UsingGradients.xaml
( 4 of 4 )
2009 Pearson Education, Inc. All rights reserved.
35
17.5 Brushes (Cont.)
• A gradient is a gradual transition through two or more colors.
– A LinearGradientBrush transitions along a straight path.
– A RadialGradientBrush transitions radially outward.
• Set RGBA values of the StartPoint and EndPoint colors of the gradient.
2009 Pearson Education, Inc. All rights reserved.
36
17.5 Brushes (Cont.)
• A GradientStop defines a single color along the gradient.
– The Color property defines the color you want the gradient to transition to.
– The Offset property defines where along the linear transition you want the color to appear.
2009 Pearson Education, Inc. All rights reserved.
37
1 // Fig. 17.7: UsingGradients.xaml.cs
2 // Customizing gradients.
3 using System;
4 using System.Windows;
5 using System.Windows.Media;
6
7 namespace UsingGradients
8 {
9 public partial class UsingGradientsWindow : Window
10 {
11 // constructor
12 public UsingGradientsWindow()
13 {
14 InitializeComponent();
15 } // end constructor
16
Outline
UsingGradients.xaml.cs
( 1 of 2 )
• The code in Fig. 17.7 allows the user to change the Colors of the two stops.
Fig. 17.7 | Customizing gradients. (Part 1 of 2.)
2009 Pearson Education, Inc. All rights reserved.
38
17 // change the starting color of the gradient when the user clicks
18 private void fromButton_Click( object sender, RoutedEventArgs e )
19 {
20 // change the color to use the ARGB values specified by user
21 startGradient.Color = Color.FromArgb(
22 Convert.ToByte( fromAlpha.Text ),
23 Convert.ToByte( fromRed.Text ),
24 Convert.ToByte( fromGreen.Text ),
25 Convert.ToByte( fromBlue.Text ) );
26 } // end method fromButton_Click
27
28 // change the ending color of the gradient when the user clicks
29 private void toButton_Click( object sender, RoutedEventArgs e )
30 {
31 // change the color to use the ARGB values specified by user
32 stopGradient.Color = Color.FromArgb(
33 Convert.ToByte( toAlpha.Text ),
34 Convert.ToByte( toRed.Text ),
35 Convert.ToByte( toGreen.Text ),
36 Convert.ToByte( toBlue.Text ) );
37 } // end method toButton_Click
38 } // end class UsingGradientsWindow
39 } // end namespace UsingGradients
Outline
UsingGradients.xaml.cs
( 2 of 2 )Obtaining the input values and creating a new color.
Obtaining the input values and creating a new color.
Fig. 17.7 | Customizing gradients. (Part 2 of 2.)
2009 Pearson Education, Inc. All rights reserved.
39
17.6 Transforms
• A transform can be applied to reposition or reorient any UI element.
– A TranslateTransform moves an object to a new location.
– A RotateTransform rotates the object around a point.
– A SkewTransform skews (or shears) the object.
– A ScaleTransform scales the object.
2009 Pearson Education, Inc. All rights reserved.
40
1 <!-- Fig. 17.8: DrawStars.xaml -->
2 <!-- Defining a Polygon representing a star in XAML. -->
3 <Window x:Class="DrawStars.DrawStarsWindow"
4 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
5 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
6 Title="DrawStars" Height="330" Width="330" Name="DrawStars">
7 <Canvas Name="mainCanvas">
8
9 <!-- Polygon with points that make up a star -->
10 <Polygon Name="star" Fill="Green" Points="205,150 217,186 259,186
11 223,204 233,246 205,222 177,246 187,204 151,186 193,186" />
12 </Canvas>
13 </Window>
Outline
DrawStars.xaml
( 1 of 2 )
• Figure 17.8 shows the XAML for an application which creates a circle of stars.
Fig. 17.8 | Defining a Polygon representing a star in XAML. (Part 1 of 2.)
Defining a single star-shaped Polygon.
2009 Pearson Education, Inc. All rights reserved.
41
Outline
DrawStars.xaml
( 2 of 2 )
Fig. 17.8 | Defining a Polygon representing a star in XAML. (Part 2 of 2.)
Original Polygon
Polygon rotated 20degrees clockwise.
2009 Pearson Education, Inc. All rights reserved.
42
1 // Fig. 17.9: DrawStars.xaml.cs
2 // Applying transforms to a Polygon.
3 using System;
4 using System.Windows;
5 using System.Windows.Media;
6 using System.Windows.Shapes;
7
8 namespace DrawStars
9 {
10 public partial class DrawStarsWindow : Window
11 {
12 // constructor
13 public DrawStarsWindow()
14 {
15 InitializeComponent();
16
17 Random random = new Random(); // get random values for colors
18
Outline
DrawStars.xaml.cs
( 1 of 2 )
• We replicate star 18 times and apply RotateTransforms to create the circle of stars (Fig. 17.9).
Fig. 17.9 | Applying transforms to a Polygon. (Part 1 of 2.)
2009 Pearson Education, Inc. All rights reserved.
43
19 // create 18 more stars
20 for ( int count = 0; count < 18; count++ )
21 {
22 Polygon newStar = new Polygon(); // create a polygon object
23 newStar.Points = star.Points; // copy the points collection
24
25 byte[] colorValues = new byte[ 4 ]; // create a Byte array
26 random.NextBytes( colorValues ); // create four random values
27 newStar.Fill = new SolidColorBrush( Color.FromArgb(
28 colorValues[ 0 ], colorValues[ 1 ], colorValues[ 2 ],
29 colorValues[ 3 ] ) ); // creates a random color brush
30
31 // apply a rotation to the shape
32 RotateTransform rotate =
33 new RotateTransform( count * 20, 150, 150 );
34 newStar.RenderTransform = rotate;
35 mainCanvas.Children.Add( newStar );
36 } // end for
37 } // end constructor
38 } // end class DrawStarsWindow
39 } // end namespace DrawStars
Outline
Duplicating star.
Using the Random class’s NextBytes method to create random ARGB colors.
Creating and applying a RotateTransform to a star filled with the new color.
Fig. 17.9 | Applying transforms to a Polygon. (Part 2 of 2.)
DrawStars.xaml.cs
( 2 of 2 )
2009 Pearson Education, Inc. All rights reserved.
44
17.7 WPF Customization: A Television GUI • The next application has a GUI that looks like a
television set.
• When the TV is on, the user can play, pause, and stop the video (Fig. 17.10).
2009 Pearson Education, Inc. All rights reserved.
45
17.7 WPF Customization: A Television GUI (Cont.)
Fig. 17.10 | GUI representing a television.
2009 Pearson Education, Inc. All rights reserved.
46
1 <!-- Fig. 17.11: TV.xaml -->
2 <!-- TV GUI showing the versatility of WPF customization. -->
3 <Window x:Class="TV.TVWindow"
4 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
5 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
6 Title="TV" Height="720" Width="720">
7 <Window.Resources>
8 <!-- define template for play, pause and stop buttons -->
9 <ControlTemplate x:Key="RadioButtonTemplate"
10 TargetType="RadioButton">
11 <Grid>
12 <!-- create a circular border -->
13 <Ellipse Width="25" Height="25" Fill="Silver" />
14
15 <!-- create an "illuminated" background -->
16 <Ellipse Name="backgroundEllipse" Width="22" Height="22">
17 <Ellipse.Fill>
18 <!-- enabled and unchecked state -->
19 <RadialGradientBrush>
Outline
TV.xaml
( 1 of 11 )
• The TV is actually just a basic WPF GUI (Fig. 17.11).
• This example demonstrates the use of WPF bitmap effects and opacity masks.
Fig. 17.11 | TV GUI showing the versatility of WPFcustomization (XAML). (Part 1 of 11.)
Creating a colorful circular template for a button.
2009 Pearson Education, Inc. All rights reserved.
47
20 <!-- red "light" -->
21 <GradientStop Offset="0" Color="Red" />
22 <GradientStop Offset="1.25" Color="Black" />
23 </RadialGradientBrush>
24 </Ellipse.Fill>
25 </Ellipse>
26
27 <!-- display button image -->
28 <ContentPresenter Content="{TemplateBinding Content}" />
29 </Grid>
30
31 <!-- change appearance when state changes -->
32 <ControlTemplate.Triggers>
33 <!-- disabled state -->
34 <Trigger Property="RadioButton.IsEnabled" Value="False">
35 <Setter TargetName="backgroundEllipse" Property="Fill">
36 <Setter.Value>
37 <RadialGradientBrush>
38 <!-- dim "light" -->
Outline
Creating a colorful circular template for a button.
Creating a dark circular template for a button (representing off).
Fig. 17.11 | TV GUI showing the versatility of WPFcustomization (XAML). (Part 2 of 11.)
TV.xaml
( 2 of 11 )
2009 Pearson Education, Inc. All rights reserved.
48
39 <GradientStop Offset="0" Color="LightGray" />
40 <GradientStop Offset="1.25" Color="Black" />
41 </RadialGradientBrush>
42 </Setter.Value>
43 </Setter>
44 </Trigger>
45
46 <!-- checked state -->
47 <Trigger Property="RadioButton.IsChecked" Value="True">
48 <Setter TargetName="backgroundEllipse" Property="Fill">
49 <Setter.Value>
50 <RadialGradientBrush>
51 <!-- green "light" -->
52 <GradientStop Offset="0" Color="LimeGreen" />
53 <GradientStop Offset="1.25" Color="Black" />
54 </RadialGradientBrush>
55 </Setter.Value>
56 </Setter>
57 </Trigger>
58 </ControlTemplate.Triggers>
59 </ControlTemplate>
60 </Window.Resources>
Outline
Creating a dark circular template for a button (representing off).
Creating a colorful circular template for a button.
Fig. 17.11 | TV GUI showing the versatility of WPFcustomization (XAML). (Part 3 of 11.)
TV.xaml
( 3 of 11 )
2009 Pearson Education, Inc. All rights reserved.
49
61
62 <!-- define the GUI -->
63 <Canvas>
64 <!-- define the "TV" -->
65 <Border Canvas.Left="150" Height="370" Width="490"
66 Canvas.Top="20" Background="DimGray">
67 <Grid>
68 <Grid.RowDefinitions>
69 <RowDefinition />
70 <RowDefinition Height="Auto" />
71 </Grid.RowDefinitions>
72
73 <!-- define the screen -->
74 <Border Margin="0,20,0,10" Background="Black"
75 HorizontalAlignment="Center" VerticalAlignment="Center"
76 BorderThickness="2" BorderBrush="Silver" CornerRadius="2">
77 <MediaElement Height="300" Width="400"
78 Name="videoMediaElement" Source="Video/future_nasa.wmv"
79 LoadedBehavior="Manual" Stretch="Fill" />
80 </Border>
81
Outline
Allowing programmatic control of playback.
Fig. 17.11 | TV GUI showing the versatility of WPFcustomization (XAML). (Part 4 of 11.)
TV.xaml
( 4 of 11 )
2009 Pearson Education, Inc. All rights reserved.
50
82 <!-- define the play, pause, and stop buttons -->
83 <StackPanel Grid.Row="1" HorizontalAlignment="Right"
84 Orientation="Horizontal">
85 <RadioButton Name="playRadioButton" IsEnabled="False"
86 Margin="0,0,5,15" Checked="playRadioButton_Checked"
87 Template="{StaticResource RadioButtonTemplate}">
88 <Image Height="20" Width="20"
89 Source="Images/play.png" Stretch="Uniform" />
90 </RadioButton>
91 <RadioButton Name="pauseRadioButton" IsEnabled="False"
92 Margin="0,0,5,15" Checked="pauseRadioButton_Checked"
93 Template="{StaticResource RadioButtonTemplate}">
94 <Image Height="20" Width="20"
95 Source="Images/pause.png" Stretch="Uniform" />
96 </RadioButton>
97 <RadioButton Name="stopRadioButton" IsEnabled="False"
98 Margin="0,0,15,15" Checked="stopRadioButton_Checked"
99 Template="{StaticResource RadioButtonTemplate}">
100 <Image Height="20" Width="20"
101 Source="Images/stop.png" Stretch="Uniform" />
102 </RadioButton>
103 </StackPanel>
Outline
Fig. 17.11 | TV GUI showing the versatility of WPFcustomization (XAML). (Part 5 of 11.)
TV.xaml
( 5 of 11 )
2009 Pearson Education, Inc. All rights reserved.
51
104
105 <!-- define the power button -->
106 <CheckBox Name="powerCheckBox" Grid.Row="1" Width="25"
107 Height="25" HorizontalAlignment="Left"
108 Margin="15,0,0,15" Checked="powerCheckBox_Checked"
109 Unchecked="powerCheckBox_Unchecked">
110 <!-- set the template -->
111 <CheckBox.Template>
112 <ControlTemplate TargetType="CheckBox">
113 <Grid>
114 <!-- create a circular border -->
115 <Ellipse Width="25" Height="25"
116 Fill="Silver" />
117
118 <!-- create an "illuminated" background -->
119 <Ellipse Name="backgroundEllipse" Width="22"
120 Height="22">
121 <Ellipse.Fill>
122 <!-- unchecked state -->
123 <RadialGradientBrush>
Outline
Creating a dark circular template for a button (representing off).
Fig. 17.11 | TV GUI showing the versatility of WPFcustomization (XAML). (Part 6 of 11.)
TV.xaml
( 6 of 11 )
2009 Pearson Education, Inc. All rights reserved.
52
124 <!-- dim "light" -->
125 <GradientStop Offset="0"
126 Color="LightGray" />
127 <GradientStop Offset="1.25"
128 Color="Black" />
129 </RadialGradientBrush>
130 </Ellipse.Fill>
131 </Ellipse>
132
133 <!-- display power button image-->
134 <Image Source="Images/power.png" Width="20"
135 Height="20" />
136 </Grid>
137
138 <!-- change appearance when state changes -->
139 <ControlTemplate.Triggers>
140 <!-- checked state -->
141 <Trigger Property="CheckBox.IsChecked"
142 Value="True">
143 <Setter TargetName="backgroundEllipse"
144 Property="Fill">
145 <Setter.Value>
Outline
Creating a dark circular template for a button (representing off).
Fig. 17.11 | TV GUI showing the versatility of WPFcustomization (XAML). (Part 7 of 11.)
TV.xaml
( 7 of 11 )
2009 Pearson Education, Inc. All rights reserved.
53
146 <!-- green "light" -->
147 <RadialGradientBrush>
148 <GradientStop Offset="0"
149 Color="LimeGreen" />
150 <GradientStop Offset="1.25"
151 Color="Black" />
152 </RadialGradientBrush>
153 </Setter.Value>
154 </Setter>
155 </Trigger>
156 </ControlTemplate.Triggers>
157 </ControlTemplate>
158 </CheckBox.Template>
159 </CheckBox>
160 </Grid>
161
162 <!-- skew "TV" to give a 3D appearance -->
163 <Border.RenderTransform>
164 <SkewTransform AngleY="15" />
165 </Border.RenderTransform>
166
Outline
Creating a colorful circular template for a button.
Fig. 17.11 | TV GUI showing the versatility of WPFcustomization (XAML). (Part 8 of 11.)
TV.xaml
( 8 of 11 )
2009 Pearson Education, Inc. All rights reserved.
54
167 <!-- apply bitmap effects to "TV" -->
168 <Border.BitmapEffect>
169 <BitmapEffectGroup>
170 <!-- make "TV" panel look "raised" -->
171 <BevelBitmapEffect BevelWidth="10" />
172
173 <!-- create a drop shadow -->
174 <DropShadowBitmapEffect Color="Gray" ShadowDepth="15"
175 Softness="1"/>
176 </BitmapEffectGroup>
177 </Border.BitmapEffect>
178 </Border>
179
180 <!-- define reflection -->
181 <Border Canvas.Left="185" Canvas.Top="410" Height="300"
182 Width="400">
183 <Rectangle Name="reflectionRectangle">
184 <Rectangle.Fill>
Outline
Applying bitmap effects for a 3-D appearance.
Fig. 17.11 | TV GUI showing the versatility of WPFcustomization (XAML). (Part 9 of 11.)
TV.xaml
( 9 of 11 )
2009 Pearson Education, Inc. All rights reserved.
55
185 <!-- create a reflection of the video -->
186 <VisualBrush
187 Visual="{Binding ElementName=videoMediaElement}">
188 <VisualBrush.RelativeTransform>
189 <ScaleTransform ScaleY="-1" CenterY="0.5" />
190 </VisualBrush.RelativeTransform>
191 </VisualBrush>
192 </Rectangle.Fill>
193
194 <!-- make reflection more transparent the further it gets
195 from the screen -->
196 <Rectangle.OpacityMask>
197 <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
198 <GradientStop Color="Black" Offset="-0.25" />
199 <GradientStop Color="Transparent" Offset="0.5" />
200 </LinearGradientBrush>
201 </Rectangle.OpacityMask>
202 </Rectangle>
203
Outline
Creating a reflection with a ScaleTransform effect.
To achieve a semitransparent look, we apply an opacity mask to the reflection.
Fig. 17.11 | TV GUI showing the versatility of WPFcustomization (XAML). (Part 10 of 11.)
TV.xaml
( 10 of 11 )
2009 Pearson Education, Inc. All rights reserved.
56
204 <!-- skew reflection to look 3D -->
205 <Border.RenderTransform>
206 <SkewTransform AngleY="15" AngleX="-45"/>
207 </Border.RenderTransform>
208 </Border>
209 </Canvas>
210 </Window>
Outline
Tilting the display for a 3-D appearance.
Bevel
Dropshadow
Fig. 17.11 | TV GUI showing the versatility of WPFcustomization (XAML). (Part 11 of 11.)
TV.xaml
( 11 of 11 )
2009 Pearson Education, Inc. All rights reserved.
57
WPF bitmap effects
BevelBitmapEffect “Raises” the edges of an element.
BlurBitmapEffect Blurs an element.
DropShadowBitmapEffect Gives an element a shadow.
EmbossBitmapEffect Uses changes in color to make an element appear raised out of the screen.
OuterGlowBitmapEffect Surrounds an element with a small amount of color to make it look like it’s glowing.
Fig. 17.12 | Summary of WPF bitmap effects.
17.7 WPF Customization: A Television GUI (Cont.)
2009 Pearson Education, Inc. All rights reserved.
58
17.7 WPF Customization: A Television GUI (Cont.) • You can apply a single bitmap effect to any element
by setting its BitmapEffect property.
• To apply more than one effect, you must define the effects in a BitmapEffectGroup.
• Each bitmap effect has its own set of unique properties defining its appearance.
Performance Tip 17.1Bitmap effects should be used sparingly in your applications as they can degrade your machine’s performance. As of .NET Framework 3.5 Service Pack 1 Beta, the Blur and DropShadow bitmap effects are hardware accelerated but performance may still be compromised.
2009 Pearson Education, Inc. All rights reserved.
59
• The TV panel is represented by a beveled Border with a gray background.
• Nested within the TV panel is another Border containing the MediaElement.
• The power button is placed in the bottom-left corner, and the playback buttons are bound in a StackPanel.
17.7 WPF Customization: A Television GUI (Cont.)
2009 Pearson Education, Inc. All rights reserved.
60
• The GUI’s video reflection is a Rectangle element nested in a Border.
• You can invert an element by setting the ScaleX or ScaleY to a negative number.
• CenterX and CenterY specify the point that the image expands or contracts from.
• To achieve a semitransparent look, we apply an opacity mask to the reflection.
17.7 WPF Customization: A Television GUI (Cont.)
2009 Pearson Education, Inc. All rights reserved.
61
• When you draw a three-dimensional object, you are creating a 2-D projection of that 3-D environment.
• The TV GUI is a 2-D orthographic projection with the axes 105, 120, and 135 degrees from each other, as shown in Fig. 17.13.
17.7 WPF Customization: A Television GUI (Cont.)
2009 Pearson Education, Inc. All rights reserved.
62
17.7 WPF Customization: A Television GUI (Cont.)
Fig. 17.13 | The effect of skewing the TV application’s GUI components.
2009 Pearson Education, Inc. All rights reserved.
63
1 // Fig. 17.14: TV.xaml.cs
2 // TV GUI showing the versatility of WPF customization (code-behind).
3 using System.Windows;
4
5 namespace TV
6 {
7 public partial class TVWindow : Window
8 {
9 // constructor
10 public TVWindow()
11 {
12 InitializeComponent();
13 } // end constructor
14
Outline
TV.xaml.cs
( 1 of 4 )
• Figure 17.14 presents the code-behind class that provides the functionality for the TV application.
Fig. 17.14 | TV GUI showing the versatility of WPF customization(code-behind). (Part 1 of 4.)
2009 Pearson Education, Inc. All rights reserved.
64
15 // turns "on" the TV
16 private void powerCheckBox_Checked( object sender,
17 RoutedEventArgs e )
18 {
19 // render the reflection visible
20 reflectionRectangle.Visibility = Visibility.Visible;
21
22 // enable play, pause, and stop buttons
23 playRadioButton.IsEnabled = true;
24 pauseRadioButton.IsEnabled = true;
25 stopRadioButton.IsEnabled = true;
26 } // end method powerCheckBox_Checked
27
28 // turns "off" the TV
29 private void powerCheckBox_Unchecked( object sender,
30 RoutedEventArgs e )
31 {
32 // shut down the screen
33 videoMediaElement.Close();
34
Outline
When the TV is turned on, the reflection is visible and playback options are enabled.
Fig. 17.14 | TV GUI showing the versatility of WPF customization(code-behind). (Part 2 of 4.)
TV.xaml.cs
( 2 of 4 )
2009 Pearson Education, Inc. All rights reserved.
65
35 // hide the reflection
36 reflectionRectangle.Visibility = Visibility.Hidden;
37
38 // disable the play, pause, and stop buttons
39 playRadioButton.IsChecked = false;
40 pauseRadioButton.IsChecked = false;
41 stopRadioButton.IsChecked = false;
42 playRadioButton.IsEnabled = false;
43 pauseRadioButton.IsEnabled = false;
44 stopRadioButton.IsEnabled = false;
45 } // end method powerCheckBox_Unchecked
46
47 // plays the video
48 private void playRadioButton_Checked( object sender,
49 RoutedEventArgs e )
50 {
51 videoMediaElement.Play();
52 } // end method playRadioButton_Checked
Outline
When the TV is turned off, the Close method is called, the reflection is made invisible and the playback options are disabled.
When a RadioButton is checked, the MediaElement executes the corresponding task.
Fig. 17.14 | TV GUI showing the versatility of WPF customization(code-behind). (Part 3 of 4.)
TV.xaml.cs
( 3 of 4 )
2009 Pearson Education, Inc. All rights reserved.
66
53
54 // pauses the video
55 private void pauseRadioButton_Checked( object sender,
56 RoutedEventArgs e )
57 {
58 videoMediaElement.Pause();
59 } // end method pauseRadioButton_Checked
60
61 // stops the video
62 private void stopRadioButton_Checked( object sender,
63 RoutedEventArgs e )
64 {
65 videoMediaElement.Stop();
66 } // end method stopRadioButton_Checked
67 } // end class TVWindow
68 } // end namespace TV
Outline
When a RadioButton is checked, the MediaElement executes the corresponding task.
When a RadioButton is checked, the MediaElement executes the corresponding task.
Fig. 17.14 | TV GUI showing the versatility of WPF customization(code-behind). (Part 4 of 4.)
TV.xaml.cs
( 4 of 4 )
2009 Pearson Education, Inc. All rights reserved.
67
1 <!-- Fig. 17.15: UsingAnimations.xaml -->
2 <!-- Animating graphic elements with Storyboards. -->
3 <Window x:Class="UsingAnimations.UsingAnimationsWindow"
4 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
5 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
6 Title="UsingAnimations" Height="400" Width="500">
7 <Grid>
8 <Grid.ColumnDefinitions>
9 <ColumnDefinition />
10 <ColumnDefinition Width="Auto" />
11 </Grid.ColumnDefinitions>
12
13 <!-- Animated video -->
14 <MediaElement Name="video" Height="100" Width="100" Stretch="Fill"
15 Source="newfractal.wmv" />
16
17 <StackPanel Grid.Column="1">
18 <!-- TextBox will contain the new Width for the video -->
19 <TextBlock Margin="5,0,0,0">Width:</TextBlock>
20 <TextBox Name="widthValue" Width="75" Margin="5">100</TextBox>
Outline
UsingAnimations.xaml
( 1 of 5 )
• An animation in WPF is a transition of a property from one value to another in a specified amount of time.
• The UsingAnimations example (Fig. 17.15) shows a video’s size being animated.
Fig. 17.15 | Animating the width and height of a video. (Part 1 of 5.)
Fill resizes the media to that of its enclosure.
2009 Pearson Education, Inc. All rights reserved.
68
21
22 <!-- TextBox will contain the new Height for the video -->
23 <TextBlock Margin="5,0,0,0">Height:</TextBlock>
24 <TextBox Name="heightValue" Width="75" Margin="5">100</TextBox>
25
26 <!-- When clicked, rectangle animates to the input values -->
27 <Button Width="75" Margin="5">Animate
28 <Button.Triggers>
29 <!-- When button is clicked -->
30 <EventTrigger RoutedEvent="Button.Click">
31 <BeginStoryboard>
32 <Storyboard Storyboard.TargetName="video">
33 <!-- Animates the Width -->
34 <DoubleAnimation Duration="0:0:2"
35 Storyboard.TargetProperty="Width"
36 To="{Binding ElementName=widthValue,
37 Path=Text}" />
38
Outline
A DoubleAnimation animates a property of type Double.
The TargetName property specifies which control to animate.
Fig. 17.15 | Animating the width and height of a video. (Part 2 of 5.)
UsingAnimations.xaml
( 2 of 5 )
2009 Pearson Education, Inc. All rights reserved.
69
39 <!-- Animates the Height -->
40 <DoubleAnimation Duration="0:0:2"
41 Storyboard.TargetProperty="Height"
42 To="{Binding ElementName=heightValue,
43 Path=Text}" />
44 </Storyboard>
45 </BeginStoryboard>
46 </EventTrigger>
47 </Button.Triggers>
48 </Button>
49 </StackPanel>
50 </Grid>
51 </Window>
Outline
A DoubleAnimation animates a property of type Double.
Fig. 17.15 | Animating the width and height of a video. (Part 3 of 5.)
UsingAnimations.xaml
( 3 of 5 )
2009 Pearson Education, Inc. All rights reserved.
70
Outline
Fig. 17.15 | Animating the width and height of a video. (Part 4 of 5.)
UsingAnimations.xaml
( 4 of 5 )
2009 Pearson Education, Inc. All rights reserved.
71
Outline
Fig. 17.15 | Animating the width and height of a video. (Part 5 of 5.)
UsingAnimations.xaml
( 5 of 5 )
2009 Pearson Education, Inc. All rights reserved.
72
• A Storyboard element contains embedded animation elements.
• A Storyboard has two important properties:– The TargetName property specifies which control to animate.
– The TargetProperty specifies which property of the animated control to change.
• Several WPF animation classes handle different property types.
17.8 Animations (Cont.)
2009 Pearson Education, Inc. All rights reserved.
73
• The Stretch property of MediaElement determines how the media fits the size of its enclosure.
– None allows the media to stay at its native size.
– Fill resizes the media to that of its enclosure.
– Uniform resizes the media to its largest possible size at its native aspect ratio.
– UniformToFill resizes the media to completely fill the container while still keeping its aspect ratio—as a result, it could be cropped.
17.8 Animations (Cont.)
2009 Pearson Education, Inc. All rights reserved.
74
1 <!-- Fig. 17.16: Application3D.xaml -->
2 <!-- Animating a 3-D object. -->
3 <Window x:Class="Application3D.Application3DWindow"
4 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
5 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
6 Title="Application3D" Height="300" Width="300">
7 <Grid>
8 <Grid.RowDefinitions>
9 <RowDefinition />
10 <RowDefinition Height="Auto" />
11 </Grid.RowDefinitions>
12
13 <Grid.Triggers>
14 <!-- when the window has loaded, begin the animation -->
15 <EventTrigger RoutedEvent="Grid.Loaded">
16 <BeginStoryboard>
17 <Storyboard Storyboard.TargetName="rotation"
18 RepeatBehavior="Forever">
19
Outline
Application3D.xaml
( 1 of 5 )
• The next example creates a rotating pyramid (Fig. 17.16).
Fig. 17.16 | Animating a 3-D object. (Part 1 of 5.)
In order to cause rotation, the Storyboard modifies the Angle property of the AxisAngleRotation3D.
Setting the RepeatBehavior of the Storyboard to Forever indicates that the animation repeats continuously.
2009 Pearson Education, Inc. All rights reserved.
75
20 <!-- rotate the object 360 degrees -->
21 <DoubleAnimation Storyboard.TargetProperty="Angle"
22 To="360" Duration="0:0:3" />
23 </Storyboard>
24 </BeginStoryboard>
25 </EventTrigger>
26 </Grid.Triggers>
27
28 <!-- viewport window for viewing the 3D object -->
29 <Viewport3D>
30 <Viewport3D.Camera>
31 <!-- camera represents what user sees -->
32 <PerspectiveCamera x:Name="camera" Position="6,0,1"
33 LookDirection="-1,0,0" UpDirection="0,0,1" />
34 </Viewport3D.Camera>
35
36 <!-- defines the 3-D content in the viewport -->
37 <ModelVisual3D>
38 <ModelVisual3D.Content>
39 <Model3DGroup>
40
Outline
Fig. 17.16 | Animating a 3-D object. (Part 2 of 5.)
Application3D.xaml
( 2 of 5 )
A Viewport3D object represents the 2-D view the user sees when the application executes.
Create a ModelVisual3D object (lines 37–75) to define a 3-D object.
The Camera property of Viewport3D defines a virtual camera.
In order to cause rotation, the Storyboard modifies the Angle property of the AxisAngleRotation3D.
2009 Pearson Education, Inc. All rights reserved.
76
41 <!-- two light sources to illuminate the objects-->
42 <DirectionalLight Color="White" Direction="-1,0,0" />
43 <DirectionalLight Color="White" Direction="0,0,-1" />
44
45 <GeometryModel3D>
46 <!-- rotate the geometry about the z-axis -->
47 <GeometryModel3D.Transform>
48 <RotateTransform3D>
49 <RotateTransform3D.Rotation>
50 <AxisAngleRotation3D x:Name="rotation"
51 Angle="0" Axis="0,0,1" />
52 </RotateTransform3D.Rotation>
53 </RotateTransform3D>
54 </GeometryModel3D.Transform>
55
56 <!-- defines the pyramid -->
57 <GeometryModel3D.Geometry>
58 <MeshGeometry3D Positions="1,1,0 1,-1,0 -1,1,0
59 -1,-1,0 0,0,2" TriangleIndices="0,4,1 2,4,0
60 3,4,2 3,1,4 2,0,1 3,2,1"
61 TextureCoordinates="0,0 1,0 0,1 1,1 0,0" />
62 </GeometryModel3D.Geometry>
Outline
Fig. 17.16 | Animating a 3-D object. (Part 3 of 5.)
Application3D.xaml
( 3 of 5 )
We use the AxisAngleRotation3D to define the transform’s rotation.
A Viewport3D object represents the 2-D view the user sees when the application executes.
Create a ModelVisual3D object (lines 37–75) to define a3-D object.
A MeshGeometry3D object specifies the exact shape of the object.
We define two DirectionalLight objects to illuminate the pyramid.
2009 Pearson Education, Inc. All rights reserved.
77
63
64 <!-- defines the surface of the object -->
65 <GeometryModel3D.Material>
66 <DiffuseMaterial>
67 <DiffuseMaterial.Brush>
68 <ImageBrush ImageSource="cover.png" />
69 </DiffuseMaterial.Brush>
70 </DiffuseMaterial>
71 </GeometryModel3D.Material>
72 </GeometryModel3D>
73 </Model3DGroup>
74 </ModelVisual3D.Content>
75 </ModelVisual3D>
76 </Viewport3D>
77
78 <!-- RadioButtons to change the axis of rotation -->
79 <GroupBox Grid.Row="1" Header="Axis of rotation">
80 <StackPanel Orientation="Horizontal"
81 HorizontalAlignment="Center">
Outline
Fig. 17.16 | Animating a 3-D object. (Part 4 of 5.)
Application3D.xaml
( 4 of 5 )
A Viewport3D object represents the 2-D view the user sees when the application executes.
Create a ModelVisual3D object (lines 37–75) to define a 3-D object.
2009 Pearson Education, Inc. All rights reserved.
78
82 <RadioButton Name="xRadio" Margin="5"
83 Checked="xRadio_Checked">x-axis</RadioButton>
84 <RadioButton Name="yRadio" Margin="5"
85 Checked="yRadio_Checked">y-axis</RadioButton>
86 <RadioButton Name="zRadio" Margin="5"
87 Checked="zRadio_Checked">z-axis</RadioButton>
88 </StackPanel>
89 </GroupBox>
90 </Grid>
91 </Window>
Outline
Fig. 17.16 | Animating a 3-D object. (Part 5 of 5.)
Application3D.xaml
( 5 of 5 )
2009 Pearson Education, Inc. All rights reserved.
79
• A Viewport3D object represents the 2-D view the user sees when the application executes.
• Create a ModelVisual3D object (lines 37–75) to define a 3-D object.
– The Content property contains the shapes you wish to define in your space.
– To add multiple objects to the Content, nest them in a Model3DGroup element.
17.9 (Optional) 3-D Objects and Transforms (Cont.)
2009 Pearson Education, Inc. All rights reserved.
80
• 3-D objects in WPF are modeled as sets of triangles.
• Shapes with flat surfaces are relatively simple to create, while curved surfaces are extremely complex.
• A MeshGeometry3D object specifies the exact shape of the object.
• Two collections are needed—one is a set of points to represent the vertices, and the other uses those vertices to specify the triangles that define the shape.
17.9 (Optional) 3-D Objects and Transforms (Cont.)
2009 Pearson Education, Inc. All rights reserved.
81
17.9 (Optional) 3-D Objects and Transforms (Cont.)
• The points are labeled in Fig. 17.17 in the order they are defined in the Positions collection.
• The text 0. (1,1,0) in the diagram refers to the first defined point.
• The TriangleIndices property specifies the three corners of each individual triangle in the collection.
• Note that we need two triangles to create the pyramid’s square base.
2009 Pearson Education, Inc. All rights reserved.
82
17.9 (Optional) 3-D Objects and Transforms (Cont.)
Fig. 17.17 | 3-D points making up a pyramid with a square base.
2009 Pearson Education, Inc. All rights reserved.
83
17.9 (Optional) 3-D Objects and Transforms (Cont.)
• The order of the corners of the triangle dictates which side is considered the “front” versus the “back.”
– If you want the surface facing toward you to be the “front,” you must define the corners in counterclockwise order.
– By default, the “front” of the triangle is drawn with your defined Material while the “back” is made transparent.
• A square can be defined using two triangles, as shown in Fig. 17.18.
2009 Pearson Education, Inc. All rights reserved.
84
17.9 (Optional) 3-D Objects and Transforms (Cont.)
Fig. 17.18 | Defining two triangles to create a square in 3-D space.
2009 Pearson Education, Inc. All rights reserved.
85
3-D materials
DiffuseMaterial Creates a “flat” surface that reflects light evenly in all directions.
SpecularMaterial Creates a glossy-looking material similar to that of metal or glass.
EmissiveMaterial Creates a glowing surface that generates its own light.
MaterialGroup Allows you to layer multiple materials.
Fig. 17.19 | 3-D materials.
• By defining the Material property of GeometryModel3D, we can specify what type of brush to use when painting each surface.
• Figure 17.19 describes controls you can use to set the Material property.
17.9 (Optional) 3-D Objects and Transforms (Cont.)
2009 Pearson Education, Inc. All rights reserved.
86
17.9 (Optional) 3-D Objects and Transforms (Cont.)
• The TextureCoordinates property defines which point is mapped onto which vertex of the object.
• The String "0,0 1,0 0,1 1,1 0,0" in the TextureCoordinates property is translated into logical points on the image.
– Logical points are expressed as coordinates from the top-left (0,0) to the bottom-right (0,1).
2009 Pearson Education, Inc. All rights reserved.
87
17.9 (Optional) 3-D Objects and Transforms (Cont.)
• The Camera property of Viewport3D defines a virtual camera.
– The Position defines the camera’s location in 3-D space.
– The LookDirection and UpDirection define the orientation of the camera.
2009 Pearson Education, Inc. All rights reserved.
88
17.9 (Optional) 3-D Objects and Transforms (Cont.)
• A 3-D object needs a virtual light source so the camera can “see” the scene.
• We define two DirectionalLight objects to illuminate the pyramid.
• This element creates uniform rays of light pointing in the direction specified by the Direction property.
2009 Pearson Education, Inc. All rights reserved.
89
17.9 (Optional) 3-D Objects and Transforms (Cont.)
• We use the RotateTransform3d class to implement a rotation of the pyramid.
• In order to cause rotation, the Storyboard modifies the Angle property of the AxisAngleRotation3D.
• Setting the RepeatBehavior of the Storyboard to Forever indicates that the animation repeats continuously.
2009 Pearson Education, Inc. All rights reserved.
90
1 // Fig. 17.20: Application3D.xaml.cs
2 // Changing the axis of rotation for a 3-D animation.
3 using System.Windows;
4 using System.Windows.Media.Media3D;
5
6 namespace Application3D
7 {
8 public partial class Application3DWindow : Window
9 {
10 // constructor
11 public Application3DWindow()
12 {
13 InitializeComponent();
14 } // end constructor
15
16 // when user selects xRadio, set axis of rotation
Outline
Application3D.xaml.cs
( 1 of 2 )
• RadioButtons at the bottom of the window change the axis of rotation (Fig. 17.20).
Fig. 17.20 | Changing the axis of rotation for a 3-D animation. (Part 1 of 2.)
2009 Pearson Education, Inc. All rights reserved.
91
17 private void xRadio_Checked( object sender, RoutedEventArgs e )
18 {
19 rotation.Axis = new Vector3D( 1, 0, 0 ); // set rotation axis
20 camera.Position = new Point3D( 6, 0, 0 ); // set camera position
21 } // end method xRadio_Checked
22
23 // when user selects yRadio, set axis of rotation
24 private void yRadio_Checked( object sender, RoutedEventArgs e )
25 {
26 rotation.Axis = new Vector3D( 0, 1, 0 ); // set rotation axis
27 camera.Position = new Point3D( 6, 0, 0 ); // set camera position
28 } // end method yRadio_Checked
29
30 // when user selects zRadio, set axis of rotation
31 private void zRadio_Checked( object sender, RoutedEventArgs e )
32 {
33 rotation.Axis = new Vector3D( 0, 0, 1 ); // set rotation axis
34 camera.Position = new Point3D( 6, 0, 1 ); // set camera position
35 } // end method zRadio_Checked
36 } // end class Application3DWindow
37 } // end namespace Application3D
Outline
Application3D.xaml.cs
( 2 of 2 )
Fig. 17.20 | Changing the axis of rotation for a 3-D animation. (Part 2 of 2.)