68
Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer http://www.minkov.it http://academy.telerik.com/ 2D and 3D Graphics and Animations WPF Graphics and Animations

5. XAML & WPF - WPF Graphics-and-Animations

Embed Size (px)

DESCRIPTION

WPF Graphics and AnimationsTelerik Software Academy: http://academy.telerik.com/school-academy/meetings/details/2012/02/02/desktop-applications-csharp-wpfThe website and all video materials are in Bulgarian.Introduction to WPF GraphicsWPF Drawing ModelResolution IndependenceBasic Graphics ObjectsBasic ShapesBitmaps, Images and EffectsBrushes and PensTransformationsAnimation

Citation preview

Page 1: 5. XAML & WPF - WPF Graphics-and-Animations

Doncho Minkov

Telerik Software Academyacademy.telerik.com

Technical Trainerhttp://www.minkov.it

http://academy.telerik.com/

2D and 3D Graphics and Animations

WPF Graphics and Animations

Page 2: 5. XAML & WPF - WPF Graphics-and-Animations

Table of Contents (2)

1. Introduction to WPF Graphics

2. WPF Drawing Model

3. Resolution Independence

4. Basic Graphics Objects

5. Basic Shapes

6. Bitmaps, Images and Effects

7. Brushes and Pens

8. Transformations

9. Animation2

Page 3: 5. XAML & WPF - WPF Graphics-and-Animations

Introduction to WPF Graphics

Page 4: 5. XAML & WPF - WPF Graphics-and-Animations

Introduction to WPF Graphics

Graphical elements can be integrated into any part of user interface

Free to mix them with any other kind of element

Use graphical elements inside controls

E.g. put an ellipse inside a button

4

Page 5: 5. XAML & WPF - WPF Graphics-and-Animations

WPF Graphics – Example

5

<DockPanel> <StackPanel DockPanel.Dock="Top" Orientation="Horizontal"> <TextBlock Text="Mix text, " /> <Ellipse Fill="red" Width="40" /> <TextBlock Text=" and " /> <Button>Controls</Button> </StackPanel> <Ellipse DockPanel.Dock="Left" Fill="Yellow" Width="100" /> <Button DockPanel.Dock="Left">z</Button> <TextBlock FontSize="24" TextWrapping="Wrap"> And of course you can put graphics into your text: <Ellipse Fill="Cyan" Width="50" Height="20" /> </TextBlock></DockPanel>

Page 6: 5. XAML & WPF - WPF Graphics-and-Animations

Introduction to WPF Graphics

Live Demo

Page 7: 5. XAML & WPF - WPF Graphics-and-Animations

WPF Drawing Model

Page 8: 5. XAML & WPF - WPF Graphics-and-Animations

WPF Drawing Model

In WPF we don't need to write a C# code to respond to redraw requests\ WPF can keep the screen repainted

for us This is because WPF lets us

represent drawings as objects that can be represented as XAML

Objects are representing graphical shapes in the tree of user interface elements When some property is changed,

WPF will automatically update the display

8

Page 9: 5. XAML & WPF - WPF Graphics-and-Animations

WPF Drawing Model –Example

9

<Canvas x:Name="MainCanvas" MouseLeftButtonDown= "mainCanvas_MouseLeftButtonDown"> <Rectangle Canvas.Left="10" Canvas.Top="30" Fill="Indigo" Width="40" Height="20" /> <Rectangle Canvas.Left="20" Canvas.Top="40" Fill="Yellow" Width="40" Height="20" /> <Rectangle Canvas.Left="30" Canvas.Top="50" Fill="Orange" Width="40" Height="20" /></Canvas>

private void MainCanvas_MouseLeftButtonDown (object sender, RoutedEventArgs e){ Rectangle r = e.Source as Rectangle; if (r != null) { r.Width += 10; }}

Page 10: 5. XAML & WPF - WPF Graphics-and-Animations

WPF Drawing ModelLive Demo

Page 11: 5. XAML & WPF - WPF Graphics-and-Animations

Resolution Independence,

Scaling and Rotation

Page 12: 5. XAML & WPF - WPF Graphics-and-Animations

Resolution Independence

What is resolution independence? Elements on the screen can be

drawn at sizes independent from the pixel grid

Resizing do not affect the image quality

WPF resolution independence means that If two monitors are set to their

native resolution and each of them is accurately reporting its DPI settings to WPF

They will display the same WPF window at the exactly the same size

12

Page 13: 5. XAML & WPF - WPF Graphics-and-Animations

Resolution Independence (2)

WPF is resolution independent, but it has logical units to give elements size

A WPF window and all the elements inside it are using device-independent units

WPF defines a device-independent pixel as 1/96th of an inch

WPF optimizes its rendering of graphical features for any scale It is ideally placed to take

advantage of increasing screen resolutions

13

Page 14: 5. XAML & WPF - WPF Graphics-and-Animations

Scaling and Rotation WPF supports transformations at a fundamental level

Everything in the UI can be transformed Not just the user-drawn graphics E.g. text, images, graphical objects,

lines, ellipses, rectangles, controls, etc.

The LayoutTransform property Available on all user interface

elements in WPF Rotation, scaling, effects (e.g. blur),

etc.

14

Page 15: 5. XAML & WPF - WPF Graphics-and-Animations

Scaling and Rotation (2)

The details have become crisper Graphic is clearer

Because WPF has rendered the button to look as good as it can at the specified size

15

<Button> <Button.LayoutTransform> <ScaleTransform ScaleX="2" ScaleY="2" /> </Button.LayoutTransform> ... <!--The result is--></Button> <!--without scaling--> <!--with scaling-->

Page 16: 5. XAML & WPF - WPF Graphics-and-Animations

Basic Graphical Objects

Page 17: 5. XAML & WPF - WPF Graphics-and-Animations

Shapes, Brushes, and Pens

Most of the classes in WPF’s drawing toolkit fall into one of these three categories: Shapes – geometrical figures, e.g.

rectangle Brushes – mechanisms to fill a

shape Pens – draw the shape borders

Shapes are objects that provide the basic building blocks for drawing Rectangle, Ellipse, Line, Polyline, Polygon, and Path

17

Page 18: 5. XAML & WPF - WPF Graphics-and-Animations

Shapes, Brushes, and Pens (2)

The simplest brush is the single-color SolidColorBrush

For more interesting visual effects use LinearGradientBrush RadialGradientBrush

Create brushes based on images ImageBrush DrawingBrush

VisualBrush – take any visual tree 18

Page 19: 5. XAML & WPF - WPF Graphics-and-Animations

Shapes, Brushes, and Pens (3)

Pens are used to draw the outline of a shape Pen is just an augmented brush

When you create a Pen object You give it a Brush to tell it how it

should paint onto the screen The Pen class adds more settings

Line thickness (1px, 2px, …) Dash patterns (solid, dotted,

dashed, …)19

Page 20: 5. XAML & WPF - WPF Graphics-and-Animations

Basic WPF Shapes

Page 21: 5. XAML & WPF - WPF Graphics-and-Animations

Base Shape Class Properties

The Fill property Specifies the Brush that will be used

to paint the interior The Stroke property

Specifies the Brush that will be used to paint the outline of the shape

The Stretch property How the shape is stretched to fill

the shape object's layout space

21

Page 22: 5. XAML & WPF - WPF Graphics-and-Animations

Rectangle

It can be drawn either filled in shape, as an outline, or both filled in and outlined

Rectangle doesn’t provide any properties for setting its location The location is determined by the

container (e.g. Canvas, StackPanel, FlowPanel, …)

22

<Canvas> <Rectangle Fill="Yellow" Stroke="Black" Canvas.Left="30" Canvas.Top="10" Width="100" Height="20" /></Canvas>

Page 23: 5. XAML & WPF - WPF Graphics-and-Animations

Rectangle (2) A Rectangle will usually be aligned with the coordinate system of its parent panel If the parent panel has been

rotated, Rectangle will of course be also rotated

RadiusX and RadiusY properties Draw a rectangle with rounded

corners RenderTransform property

Transforms a Rectangle relative to its containing panel (rotate, scale, effects, …)

23

Page 24: 5. XAML & WPF - WPF Graphics-and-Animations

Ellipse

Ellipse is similar to Rectangle Size, location, rotation, fill, and stroke of an Ellipse are controlled in exactly the same way as for a Rectangle

24

<Ellipse Width="100" Height="50" Fill="Yellow" Stroke="Black" />

<!--The result is-->

Page 25: 5. XAML & WPF - WPF Graphics-and-Animations

Line Draws a straight line between two points

Controlling the location X1 and Y1 define the start point,

and X2 and Y2 determine the end point

25

<StackPanel Orientation="Vertical"> <TextBlock Background="LightGray">Foo</TextBlock> <Line Stroke="Green" X1="20" Y1="10" X2="100" Y2="40" /> <TextBlock Background="LightGray">Bar</TextBlock> <Line Stroke="Green" X1="0" Y1="10" X2="100" Y2="0" /></StackPanel>

Page 26: 5. XAML & WPF - WPF Graphics-and-Animations

Ellipses and LinesLive Demo

Page 27: 5. XAML & WPF - WPF Graphics-and-Animations

Polyline Draw a connected series of line segments

Points property Containing a list of coordinate pairs

27

<Polyline Stroke="Blue" Points="0,30 10,30 15,0 18,60 23,30 35,30 40,0 43,60 48,30 160,30" />

<!--The result is-->

Page 28: 5. XAML & WPF - WPF Graphics-and-Animations

Polygon Polygon is very similar to Polyline

It has a Points property that works in exactly the same way as Polyline’s

Polygon always draws a closed shape

28

<Polyline Fill="Orange" Stroke="Blue" StrokeThickness="2" Points="40,10 70,50 10,50" /><Polygon Fill="Orange" Stroke="Blue" StrokeThickness="2" Points="40,10 70,50 10,50" />

<!--The result is-->

Page 29: 5. XAML & WPF - WPF Graphics-and-Animations

Polygon (2) FillRule property

If this number is odd, the point was inside the shape

If it is even, the point is outside the shape

The default rule is EvenOdd

29

<Polygon Fill="Orange" Stroke="Blue" StrokeThickness="2" FillRule="Nonzero" Points="10,10 60,10 60,25 20,25 20,40 40,40 40,18 50,18 50,50 10,50" /> <!--The result is-->

Page 30: 5. XAML & WPF - WPF Graphics-and-Animations

Path Path draws more complex shapes Data property specifies the Geometry

Three geometry types RectangleGeometry

Correspond to the Rectangle

EllipseGeometry Correspond to the Ellipse

LineGeometry Correspond to the Line 30

Page 31: 5. XAML & WPF - WPF Graphics-and-Animations

Path (2) GeometryGroup object

Create a shape with multiple geometries

31

<Canvas> <Path Fill="Cyan" Stroke="Black"> <Path.Data> <GeometryGroup> <EllipseGeometry Center="20, 40" RadiusX="20" RadiusY="40" /> <EllipseGeometry Center="20, 40" RadiusX="10" RadiusY="30" /> </GeometryGroup> </Path.Data> <!--The result is--> </Path></Canvas>

Page 32: 5. XAML & WPF - WPF Graphics-and-Animations

PathLive Demo

Page 33: 5. XAML & WPF - WPF Graphics-and-Animations

Path (3) The ArcSegment

Add elliptical curves to the edge of a shape

Provides two flags IsLargeArc – determines whether you

get the larger or smaller slice size

SweepDirection – chooses on which side of the line the slice is drawn

Draw Bézier curves and combining shapes

33

Page 34: 5. XAML & WPF - WPF Graphics-and-Animations

Arc Segment – Example

34

<Path Fill="Cyan" Stroke="Black"> <Path.Data> <PathGeometry> <PathFigure StartPoint="0,11" IsClosed="True"> <ArcSegment Point="50,61" Size="70,30" SweepDirection="Counterclockwise" /> </PathFigure> <PathFigure StartPoint="30,11" IsClosed="True"> <ArcSegment Point="80,61" Size="70,30" SweepDirection="Clockwise" IsLargeArc="True" /> </PathFigure> </PathGeometry> <!--The result is--> </Path.Data></Path>

Page 35: 5. XAML & WPF - WPF Graphics-and-Animations

ArcSegmentLive Demo

Page 36: 5. XAML & WPF - WPF Graphics-and-Animations

Bitmaps, Images and

Effects

Page 37: 5. XAML & WPF - WPF Graphics-and-Animations

Image Image simply displays a picture Place image anywhere in the visual

tree Source property

URL of the image file / resource Setting the Source property to an

absolute URL

Using relative URL37

<Image Source="http://www.interact-sw.co.uk/images/M3/BackOfM3.jpeg" />

<Image Source="/MyFunnyImage.jpeg" />

Page 38: 5. XAML & WPF - WPF Graphics-and-Animations

Image (2) The Image element is able to resize the image

The default scaling behavior Use the same scale factor

horizontally and vertically Stretch property

The image will fill the entire space of its container

38

<Image Source="/MyFunnyImage.jpeg" Stretch="Fill" Opacity="0.5" />

Page 39: 5. XAML & WPF - WPF Graphics-and-Animations

ImageSource ImageSource is an abstract base class Represent an image

Two classes derive from ImageSource DrawingImage

It wraps a resolution-independent drawing object

BitmapSource – it also is abstract Bitmap source types: BitmapFrame, BitmapImage, CachedBitmap, ColorConvertedBitmap, etc.

39

Page 40: 5. XAML & WPF - WPF Graphics-and-Animations

Creating Bitmaps RenderTargetBitmap

Create a new bitmap from any visual

40

RenderTargetBitmap bmp = new RenderTargetBitmap(300,150,300,300, PixelFormats.Pbgra32);Ellipse e = new Ellipse();e.Fill = Brushes.Green;e.Measure(new Size(96, 48));e.Arrange(new Rect(0, 0, 96, 48));bmp.Render(e); <!-- The result is -->

Page 41: 5. XAML & WPF - WPF Graphics-and-Animations

Creating Bitmaps (2) You can choose any resolution you like for the output

RenderTargetBitmap lets you build a bitmap out of any combination of WPF visuals

It is great if you want to build or modify a bitmap using WPF elements

41

Page 42: 5. XAML & WPF - WPF Graphics-and-Animations

Bitmap Effects BitmapEffects property

Apply a visual effect to the element and all of its children

All of these effects use bitmap processing algorithms

42

<StackPanel Orientation="Horizontal"> <StackPanel Orientation="Vertical"> <TextBlock Text="Normal Text" TextAlignment="Center" FontWeight="Bold" /> <RadioButton Content="Better in position 1?" GroupName="r" /> </StackPanel><!--The example continues-->

Page 43: 5. XAML & WPF - WPF Graphics-and-Animations

Bitmap Effects (2)

The built-in effects BevelBitmapEffect BitmapEffectGroup BlurBitmapEffect …

43

<StackPanel Orientation="Vertical" Margin="10,0"> <StackPanel.BitmapEffect> <BlurBitmapEffect Radius="3" /> </StackPanel.BitmapEffect> <TextBlock Text="Blurred Text" TextAlignment="Center" FontWeight="Bold" /> <RadioButton Content="Or position 2?" GroupName="r" /> </StackPanel></StackPanel>

Page 44: 5. XAML & WPF - WPF Graphics-and-Animations

Bitmap EffectsLive Demo

Page 45: 5. XAML & WPF - WPF Graphics-and-Animations

Brushes and Pens

Page 46: 5. XAML & WPF - WPF Graphics-and-Animations

SolidColorBrush SolidColorBrush uses one color across the whole area being painted It has just one property – Color

The XAML compiler will recognize Yellow as one of the standard named colors from the Colors class

Uses a numeric color value Begin with a # symbol and contain

hexadecimal digits – Fill="#8F8" 46

<Rectangle Fill="Yellow" Width="100" Height="20" />

Page 47: 5. XAML & WPF - WPF Graphics-and-Animations

LinearGradientBrush The painted area transitions from one color to another

The StartPoint and EndPoint properties Indicate where the color transition

begins and ends These coordinates are relative to

the area being filled

47

Page 48: 5. XAML & WPF - WPF Graphics-and-Animations

LinearGradientBrush (2)

Each GradientStop has an Offset property Enables the fill to pass through

multiple colors 48

<Rectangle Width="80" Height="60"><Rectangle.Fill> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> <GradientStop Color="Blue" Offset="0" /> <GradientStop Color="White" Offset="1" /> </LinearGradientBrush> <!--The result is--> </Rectangle.Fill></Rectangle>

Page 49: 5. XAML & WPF - WPF Graphics-and-Animations

ImageBrush TileBrush

Base class for ImageBrush, DrawingBrush, and VisualBrush

Decides how to stretch the source image to fill the available space

Stretch property Specifies how the content of this TileBrush stretches to fit its tiles

Fill / Uniform / UniformToFill

49

Page 50: 5. XAML & WPF - WPF Graphics-and-Animations

ImageBrush (2) AlignmentX and AlignmentY properties Horizontal and vertical alignment of

content in the TileBrush base tile Viewbox, Viewport, ViewboxUnits, and ViewportUnits properties Allow you to focus on any part of

the image or choose specific scale factors

TileMode property50

Page 51: 5. XAML & WPF - WPF Graphics-and-Animations

ImageBrushLive Demo

Page 52: 5. XAML & WPF - WPF Graphics-and-Animations

Pen A Pen is always based on a brush

Accessed through Stroke property Describes how a shape is outlined Important properties

Thickness and DashArray properties

52

<Rectangle Stroke="Black" StrokeThickness="5" StrokeDashArray="10 1 3 1" /><Rectangle Stroke="Black" StrokeThickness="5" StrokeDashArray="6 1 6" />

Page 53: 5. XAML & WPF - WPF Graphics-and-Animations

Transformations

Page 54: 5. XAML & WPF - WPF Graphics-and-Animations

Transform Classes

TranslateTransform – displaces the coordinate system by some amount

RotateTransform – rotates coordinate system Angle, CenterX, CenterY properties

54

<Button Width="180" Height="60" Canvas.Left="100" Canvas.Top="100">I'm rotated 35 degrees <Button.RenderTransform> <RotateTransform Angle="35" CenterX="45" CenterY="5" /> </Button.RenderTransform></Button>

Page 55: 5. XAML & WPF - WPF Graphics-and-Animations

Transform Classes ScaleTransform – scales the coordinate system up or down ScaleX, ScaleY, CenterX, CenterY

properties SkewTransform – warps your coordinate system by slanting it a number of degrees AngleX, AngleY, CenterX, CenterX

MatrixTransform – modifies the coordinate system using matrix multiplication Matrix property

55

Page 56: 5. XAML & WPF - WPF Graphics-and-Animations

TransformationsLive Demo

Page 57: 5. XAML & WPF - WPF Graphics-and-Animations

XAML-Based Animation

Page 58: 5. XAML & WPF - WPF Graphics-and-Animations

Animation WPF and Silverlight perform time-based animation with Storyboard Uses a property-based animation

model E.g. modify the value of a property

over an interval of time To animate a property you need to have an animation class To modify the color from some value

to another, use the ColorAnimation class

To modify a property, use DoubleAnimation

58

Page 59: 5. XAML & WPF - WPF Graphics-and-Animations

Animation – Example

59

<Canvas> <Ellipse Width="200" Height="150" Fill="Orange" x:Name="AnimatedEllipse"> <Ellipse.Triggers> <EventTrigger RoutedEvent="Ellipse.Loaded"> <BeginStoryboard><Storyboard> <DoubleAnimation Storyboard.TargetName="AnimatedEllipse" Storyboard.TargetProperty="(Canvas.Left)" From="-50" To="300" Duration="00:00:0.88" AutoReverse="True" RepeatBehavior="Forever" /> </Storyboard></BeginStoryboard> </EventTrigger> </Ellipse.Triggers> </Ellipse></Canvas>

Page 60: 5. XAML & WPF - WPF Graphics-and-Animations

AnimationLive Demo

Page 61: 5. XAML & WPF - WPF Graphics-and-Animations

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?http://academy.telerik.com

WPF Graphics and Animations

Page 62: 5. XAML & WPF - WPF Graphics-and-Animations

Exercises1. Write a program that visualize this

figure. Use only rectangles and RenderTransform.

2. Draw the rectangles from the previous exercise with rounded corners.

3. Write a WPF program that visualize the figure below. Use Polyline and Polygon

and FillRule property.

4. In the demo "Arc Segment" add rotation of 45 degrees (rotating the ellipses before slicing them).

5. Draw few national flags (e.g. Bulgarian, German, …). Make an animation that transits from one flag to another by changing the opacity of the flags.

Page 63: 5. XAML & WPF - WPF Graphics-and-Animations

Exercises (2)6. Write a WPF program that visualize a LinearGradientBrush with multiple colors (use Offset property).

7. Use TransformGroup to apply a ScaleTransform and a RotateTransform to the RenderTransform property of a TextBlock.

8. Implement Storyboard animation that moves a large blue rectangle from left to right and back. Add a counterclockwise rotation to the animation. Finally add a color-changing animation from blue to yellow.

Page 64: 5. XAML & WPF - WPF Graphics-and-Animations

Exercises (3)9. Implement a star field simulation

in WPF. The sky should be a Canvas panel with black background. The stars should be light blue circles with different size and transparency. All stars should move from top to bottom with different speed. Larger stars move faster and are less transparent.

10.Add a space ship at the bottom of the screen.

11.Make the ship move left or right by keyboard keys.

64

Page 65: 5. XAML & WPF - WPF Graphics-and-Animations

Exercises12. Create a WPF application that shows

a circle, filled in orange color with black borders.

13. Create a WPF application that shows the text “Hello world” with font family Consolas, size 100, and color blue.

14. Create a WPF application that shows three nested rectangles with in different colors.

15. Create a WPF application that shows a few rectangles with rounded corners.

16. Create a WPF application that shows all

fonts in "C:\Windows\Fonts".

65

Page 66: 5. XAML & WPF - WPF Graphics-and-Animations

Exercises (2)17. Create a WPF application that shows a

FlowDocument. The document should consist of header (show in the center of the window, with different font from the other text), a picture (floating at the top left corner) and some other text.

18.Create a WPF application that shows the lists below:

Use List and MarkerStyle, StartIndex properties.

Page 67: 5. XAML & WPF - WPF Graphics-and-Animations

Exercises (3)19. Create a WPF application that shows

the table below:

20. Create a WPF application that shows the table below:

Page 68: 5. XAML & WPF - WPF Graphics-and-Animations

Free Trainings @ Telerik Academy

Desktop Applications with C# and WPF academy.telerik.com/

Telerik Software Academy academy.telerik.com

Telerik Academy @ Facebook facebook.com/TelerikAcademy

Telerik Software Academy Forums forums.academy.telerik.com