+ All Categories
Home > Technology > WPF Graphics and Animations

WPF Graphics and Animations

Date post: 01-Sep-2014
Category:
Upload: doncho-minkov
View: 2,257 times
Download: 9 times
Share this document with a friend
Description:
 
Popular Tags:
67
2 2 D and D and 3 3 D Graphics and Animations D Graphics and Animations Doncho Minkov Doncho Minkov Telerik School Telerik School Academy Academy schoolacademy.telerik .com Technical Trainer Technical Trainer http://www.minkov.it WPF Graphics and WPF Graphics and Animations Animations
Transcript
Page 1: WPF Graphics and Animations

22D and D and 33D Graphics and AnimationsD Graphics and Animations

Doncho MinkovDoncho Minkov

Telerik School Telerik School AcademyAcademyschoolacademy.telerik.com

Technical TrainerTechnical Trainerhttp://www.minkov.it

WPF Graphics and WPF Graphics and AnimationsAnimations

Page 2: WPF Graphics and Animations

Table of Contents (2)Table of Contents (2)1.1. Introduction to WPF GraphicsIntroduction to WPF Graphics2.2. WPF Drawing ModelWPF Drawing Model3.3. Resolution IndependenceResolution Independence4.4. Basic Graphics ObjectsBasic Graphics Objects5.5. Basic ShapesBasic Shapes6.6. Bitmaps, Images and EffectsBitmaps, Images and Effects7.7. Brushes and PensBrushes and Pens8.8. TransformationsTransformations9.9. AnimationAnimation

2

Page 3: WPF Graphics and Animations

Introduction to Introduction to WPF GraphicsWPF Graphics

Page 4: WPF Graphics and Animations

Introduction to WPF Introduction to WPF GraphicsGraphics

Graphical elements can be Graphical elements can be integrated into any part of user integrated into any part of user interfaceinterface Free to mix them with any other Free to mix them with any other

kind of elementkind of element Use graphical elements inside Use graphical elements inside

controlscontrols E.g. put an ellipse inside a buttonE.g. put an ellipse inside a button

4

Page 5: WPF Graphics and Animations

WPF Graphics – WPF Graphics – ExampleExample

5

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

Page 6: WPF Graphics and Animations

Introduction to WPF Introduction to WPF GraphicsGraphics

Live DemoLive Demo

Page 7: WPF Graphics and Animations

WPF Drawing ModelWPF Drawing Model

Page 8: WPF Graphics and Animations

WPF Drawing ModelWPF Drawing Model In WPF we don't need to write a C# code In WPF we don't need to write a C# code

to respond to redraw requests\to respond to redraw requests\ WPF can keep the screen repainted for usWPF can keep the screen repainted for us This is because WPF lets us represent This is because WPF lets us represent

drawings as objects that can be drawings as objects that can be represented as XAMLrepresented as XAML

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

automatically update the displayautomatically update the display8

Page 9: WPF Graphics and Animations

WPF Drawing Model –WPF Drawing Model –ExampleExample

9

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

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

Page 10: WPF Graphics and Animations

WPF Drawing ModelWPF Drawing ModelLive DemoLive Demo

Page 11: WPF Graphics and Animations

Resolution Resolution Independence, Independence,

Scaling and RotationScaling and Rotation

Page 12: WPF Graphics and Animations

Resolution Resolution IndependenceIndependence

What is What is resolution independenceresolution independence?? Elements on the screen can be drawn at Elements on the screen can be drawn at

sizes independent from the pixel gridsizes independent from the pixel grid Resizing do not affect the image qualityResizing do not affect the image quality

WPF resolution independence means WPF resolution independence means thatthat If two monitors are set to their native If two monitors are set to their native

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

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

12

Page 13: WPF Graphics and Animations

Resolution Resolution Independence (2)Independence (2)

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

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

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

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

increasing screen resolutionsincreasing screen resolutions13

Page 14: WPF Graphics and Animations

Scaling and RotationScaling and Rotation WPF supports transformations at a WPF supports transformations at a

fundamental levelfundamental level Everything in the UI can be transformedEverything in the UI can be transformed

Not just the user-drawn graphicsNot just the user-drawn graphics E.g. text, images, graphical objects, E.g. text, images, graphical objects,

lines, ellipses, rectangles, controls, etc.lines, ellipses, rectangles, controls, etc. The The LayoutTransformLayoutTransform property property

Available on all user interface elements Available on all user interface elements in WPFin WPF

Rotation, scaling, effects (e.g. blur), etc.Rotation, scaling, effects (e.g. blur), etc.

14

Page 15: WPF Graphics and Animations

Scaling and Rotation Scaling and Rotation (2)(2)

The details have become crisperThe details have become crisper GGraphic is clearerraphic is clearer

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

15

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

Page 16: WPF Graphics and Animations

Basic Graphical Basic Graphical ObjectsObjects

Page 17: WPF Graphics and Animations

Shapes, Brushes, and Shapes, Brushes, and PensPens

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

rectanglerectangle Brushes – mechanisms to fill a shapeBrushes – mechanisms to fill a shape Pens – draw the shape bordersPens – draw the shape borders

Shapes are objectsShapes are objects that provide the that provide the basic building blocks for drawingbasic building blocks for drawing RectangleRectangle, , EllipseEllipse, , LineLine, , PolylinePolyline, , PolygonPolygon, and , and PathPath

17

Page 18: WPF Graphics and Animations

Shapes, Brushes, and Shapes, Brushes, and Pens (2)Pens (2)

The simplest brush is the single-color The simplest brush is the single-color SolidColorBrushSolidColorBrush

For more interesting visual effects For more interesting visual effects useuse LinearGradientBrushLinearGradientBrush RadialGradientBrushRadialGradientBrush

Create brushes based on imagesCreate brushes based on images ImageBrushImageBrush DDrawingBrushrawingBrush

VisualBrushVisualBrush – – taketake any visual treeany visual tree18

Page 19: WPF Graphics and Animations

Shapes, Brushes, and Shapes, Brushes, and Pens (3)Pens (3)

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

When you create a When you create a PenPen object object You give it a You give it a BrushBrush to tell it how it to tell it how it

should paint onto the screenshould paint onto the screen The The PenPen class adds more settings class adds more settings

LLine thickness (1px, 2px, …)ine thickness (1px, 2px, …) DDash patterns (solid, dotted, dashed, ash patterns (solid, dotted, dashed,

…)…)19

Page 20: WPF Graphics and Animations

Basic WPF Basic WPF ShapesShapes

Page 21: WPF Graphics and Animations

Base Shape Class Base Shape Class PropertiesProperties

The The FillFill property property Specifies the Specifies the BrushBrush that will be used that will be used

to paint the interiorto paint the interior The The StrokeStroke property property

Specifies the Specifies the BrushBrush that will be used that will be used to paint the outline of the shapeto paint the outline of the shape

The The StretchStretch property property How the shape is stretched to fill How the shape is stretched to fill

the shape object's layout spacethe shape object's layout space21

Page 22: WPF Graphics and Animations

RectangleRectangle It can be drawn either filled in It can be drawn either filled in

shape, as an outline, or both filled shape, as an outline, or both filled in and outlinedin and outlined

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

container (e.g. container (e.g. CanvasCanvas, , StackPanelStackPanel, , FlowPanelFlowPanel, …), …)

22

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

Page 23: WPF Graphics and Animations

Rectangle (2)Rectangle (2) A A RectangleRectangle will usually be aligned will usually be aligned

with the coordinate system of its with the coordinate system of its parent panelparent panel If the parent panel has been rotated, If the parent panel has been rotated, RectangleRectangle will of course be also rotated will of course be also rotated

RadiusXRadiusX and and RadiusYRadiusY properties properties Draw a rectangle with rounded cornersDraw a rectangle with rounded corners

RenderTransformRenderTransform property property Transforms a Transforms a RectangleRectangle relative to its relative to its

containing panel (rotate, scale, effects, containing panel (rotate, scale, effects, …)…)

23

Page 24: WPF Graphics and Animations

EllipseEllipse Ellipse is similar to Ellipse is similar to RectangleRectangle Size, location, rotation, fill, and Size, location, rotation, fill, and

stroke of an stroke of an EllipseEllipse are controlled are controlled in exactly the same way as for a in exactly the same way as for a RectangleRectangle

24

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

<!--The result is--><!--The result is-->

Page 25: WPF Graphics and Animations

LineLine Draws a straight line between two Draws a straight line between two

pointspoints CControlling the locationontrolling the location

X1 and Y1 define the start point, X1 and Y1 define the start point, and X2 and Y2 deterand X2 and Y2 determine the end mine the end pointpoint

25

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

Page 26: WPF Graphics and Animations

Ellipses and LinesEllipses and LinesLive DemoLive Demo

Page 27: WPF Graphics and Animations

PolylinePolyline Draw a connected series of line Draw a connected series of line

segmentssegments PointsPoints property property

Containing a list of coordinate pairsContaining a list of coordinate pairs

27

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

<!--The result is--> <!--The result is-->

Page 28: WPF Graphics and Animations

PolygonPolygon PolygonPolygon is very similar to is very similar to PolylinePolyline

It has a It has a PointsPoints property that works property that works in exactly the same way as in exactly the same way as PolylinePolyline’s’s

PolygonPolygon always draws a closed always draws a closed shapeshape

28

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

<!--The result is--> <!--The result is-->

Page 29: WPF Graphics and Animations

Polygon (2)Polygon (2) FillRuleFillRule property property

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

If it is even, the point is outside the If it is even, the point is outside the shapeshape

The default rule is The default rule is EvenOddEvenOdd

29

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

Page 30: WPF Graphics and Animations

PathPath PathPath draws more complex shapes draws more complex shapes DataData property specifies the property specifies the GeometryGeometry Three geometry typesThree geometry types

RectangleGeometryRectangleGeometry Correspond to the Correspond to the RectangleRectangle

EllipseGeometryEllipseGeometry Correspond to the Correspond to the EllipseEllipse

LineGeometryLineGeometry Correspond to the Correspond to the LineLine

30

Page 31: WPF Graphics and Animations

Path (2)Path (2) GeometryGroupGeometryGroup object object

Create a shape with multiple Create a shape with multiple geometriesgeometries

31

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

Page 32: WPF Graphics and Animations

PathPathLive DemoLive Demo

Page 33: WPF Graphics and Animations

Path (3)Path (3) The The ArcSegmentArcSegment

Add elliptical curves to the edge of a Add elliptical curves to the edge of a shapeshape

PProvides two flagsrovides two flags IsLargeArcIsLargeArc – determines whether you – determines whether you

get the larger or smaller slice sizeget the larger or smaller slice size SweepDirectionSweepDirection – chooses on which – chooses on which

side of the line the slice is drawnside of the line the slice is drawn DDrawraw BézierBézier curves curves and c and combining ombining

shapesshapes33

Page 34: WPF Graphics and Animations

Arc Segment – ExampleArc Segment – Example

34

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

Page 35: WPF Graphics and Animations

ArcSegmentArcSegmentLive DemoLive Demo

Page 36: WPF Graphics and Animations

Bitmaps, Bitmaps, Images and Images and

EffectsEffects

Page 37: WPF Graphics and Animations

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

treetree SourceSource property property

URL of the image file / resourceURL of the image file / resource Setting the Setting the SourceSource property to an property to an

absolute URLabsolute URL

Using relative URLUsing relative URL37

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

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

Page 38: WPF Graphics and Animations

ImageImage (2) (2) The The ImageImage element is able to resize element is able to resize

the imagethe image The default scaling behaviorThe default scaling behavior

Use the same scale factor Use the same scale factor horizontally and verticallyhorizontally and vertically

StretchStretch property property The image will fill the entire space The image will fill the entire space

of its containerof its container

38

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

Page 39: WPF Graphics and Animations

ImageSourceImageSource ImageSourceImageSource is an abstract base class is an abstract base class

RRepresent an imageepresent an image Two classes derive from Two classes derive from ImageSourceImageSource

DrawingImageDrawingImage It wraps a resolution-independent It wraps a resolution-independent

drawing objectdrawing object BitmapSourceBitmapSource – it also is abstract – it also is abstract

BBitmap source typesitmap source types: : BitmapFramBitmapFramee, , BitmapImagBitmapImagee, , CachedBitmapCachedBitmap, , ColorConvertedBitmaColorConvertedBitmapp, etc. , etc.

39

Page 40: WPF Graphics and Animations

Creating BitmapsCreating Bitmaps RenderTargetBitmapRenderTargetBitmap

Create a new bitmap from any Create a new bitmap from any visualvisual

40

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

Page 41: WPF Graphics and Animations

Creating BitmapsCreating Bitmaps (2) (2) You can choose any resolution you You can choose any resolution you

like for the outputlike for the output RenderTargetBitmapRenderTargetBitmap lets you build a lets you build a

bitmap out of any combination of bitmap out of any combination of WPF visualsWPF visuals

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

41

Page 42: WPF Graphics and Animations

Bitmap EffectsBitmap Effects BitmapEffectsBitmapEffects property property

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

All of these effects use bitmap All of these effects use bitmap processing algorithmsprocessing algorithms

42

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

Page 43: WPF Graphics and Animations

Bitmap Effects (2)Bitmap Effects (2)

TThe built-in effectshe built-in effects BevelBitmapEffectBevelBitmapEffect BitmapEffectGroupBitmapEffectGroup BlurBitmapEffectBlurBitmapEffect ……

43

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

Page 44: WPF Graphics and Animations

Bitmap EffectsBitmap EffectsLive DemoLive Demo

Page 45: WPF Graphics and Animations

Brushes and Brushes and PPensens

Page 46: WPF Graphics and Animations

SolidColorBrushSolidColorBrush SolidColorBrushSolidColorBrush uses one color uses one color

across the whole area being paintedacross the whole area being painted It has just one property – It has just one property – ColorColor

The XAML compiler will recognize The XAML compiler will recognize YellowYellow as one of the standard as one of the standard named colors from the named colors from the ColorsColors class class

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

hexadecimal digits – hexadecimal digits – Fill="#8F8"Fill="#8F8" 46

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

Page 47: WPF Graphics and Animations

LinearGradientBrushLinearGradientBrush The painted area transitions from The painted area transitions from

one color to anotherone color to another The The StartPointStartPoint and and EndPointEndPoint

propertiesproperties Indicate where the color transition Indicate where the color transition

begins and endsbegins and ends These coordinates are relative to These coordinates are relative to

the area being filledthe area being filled

47

Page 48: WPF Graphics and Animations

LinearGradientBrushLinearGradientBrush (2) (2)

Each Each GradientStopGradientStop has an has an OffsetOffset property property Enables the fill to pass through multiple colorsEnables the fill to pass through multiple colors

48

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

Page 49: WPF Graphics and Animations

ImageBrushImageBrush TileBrushTileBrush

Base class for Base class for ImageBrushImageBrush, , DrawingBrushDrawingBrush, and , and VisualBrushVisualBrush

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

StretchStretch property property Specifies how the content of this Specifies how the content of this TileBrushTileBrush stretches to fit its tiles stretches to fit its tiles

FillFill / / UniformUniform / / UniformToFillUniformToFill

49

Page 50: WPF Graphics and Animations

ImageBrushImageBrush (2) (2) AlignmentXAlignmentX and and AlignmentYAlignmentY

propertiesproperties Horizontal and vertical alignment of Horizontal and vertical alignment of

content in the content in the TileBrushTileBrush base tile base tile ViewboxViewbox, , ViewportViewport, , ViewboxUnitsViewboxUnits, ,

and and ViewportUnitsViewportUnits properties properties Allow you to focus on any part of Allow you to focus on any part of

the image or choose specific scale the image or choose specific scale factorsfactors

TileModeTileMode property property50

Page 51: WPF Graphics and Animations

ImageBrushImageBrushLive DemoLive Demo

Page 52: WPF Graphics and Animations

PenPen A A PenPen is always based on a brush is always based on a brush

Accessed through Accessed through StrokeStroke property property Describes how a shape is outlinedDescribes how a shape is outlined Important propertiesImportant properties

ThicknessThickness and and DashArrayDashArray propert propertiesies

52

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

Page 53: WPF Graphics and Animations

Transformations Transformations

Page 54: WPF Graphics and Animations

Transform ClassesTransform Classes TranslateTransformTranslateTransform – displaces the – displaces the

coordinate system by some amountcoordinate system by some amount RotateTransformRotateTransform – rotates – rotates

coordinate systemcoordinate system AngleAngle, , CenterXCenterX, , CenterYCenterY properties properties

54

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

Page 55: WPF Graphics and Animations

Transform ClassesTransform Classes ScaleTransformScaleTransform – scales the coordinate – scales the coordinate

system up or system up or downdown ScaleXScaleX, , ScaleYScaleY, , CenterXCenterX, , CenterYCenterY properties properties

SkewTransformSkewTransform – warps your coordinate – warps your coordinate system by slanting it a number of system by slanting it a number of degreesdegrees AngleXAngleX, , AngleYAngleY, , CenterXCenterX, , CenterXCenterX

MatrixTransformMatrixTransform – modifies the coordinate – modifies the coordinate system using matrix multiplicationsystem using matrix multiplication MatrixMatrix propertyproperty

55

Page 56: WPF Graphics and Animations

TransformationsTransformationsLive DemoLive Demo

Page 57: WPF Graphics and Animations

XAML-Based XAML-Based AAnimationnimation

Page 58: WPF Graphics and Animations

AAnimationnimation WPF and Silverlight perform time-WPF and Silverlight perform time-

based animation with based animation with StoryboardStoryboard Uses a property-based animation modelUses a property-based animation model E.g. modify the value of a property E.g. modify the value of a property

over an interval of timeover an interval of time To animate a property you need to To animate a property you need to

have an animation classhave an animation class To modify the color from some value to To modify the color from some value to

another, use the another, use the ColorAnimationColorAnimation class class To modify a property, use To modify a property, use DoubleAnimationDoubleAnimation

58

Page 59: WPF Graphics and Animations

Animation – ExampleAnimation – Example

59

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

Page 60: WPF Graphics and Animations

AAnimationimationnLive DemoLive Demo

Page 61: WPF Graphics and Animations

WPF Graphics and WPF Graphics and AnimationsAnimations

Questions?Questions?

Page 62: WPF Graphics and Animations

ExercisesExercises1.1. Write a program that visualize this figure. Write a program that visualize this figure.

Use only rectangles and Use only rectangles and RenderTransformRenderTransform..2.2. Draw the rectangles from the previousDraw the rectangles from the previous

exercise with rounded corners.exercise with rounded corners.3.3. Write a WPF program that visualize the figure Write a WPF program that visualize the figure

below. Use below. Use PolylinePolyline and and PolygonPolygon and and FillRuleFillRule property. property.

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

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

Page 63: WPF Graphics and Animations

Exercises (2)Exercises (2)6.6. Write a WPF program that visualize a Write a WPF program that visualize a LinearGradientBrushLinearGradientBrush with multiple colors with multiple colors (use (use OffsetOffset property). property).

7.7. Use Use TransformGroupTransformGroup to apply a to apply a ScaleTransformScaleTransform and a and a RotateTransformRotateTransform to the to the RenderTransformRenderTransform property of a property of a TextBlockTextBlock..

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

Page 64: WPF Graphics and Animations

Exercises (3)Exercises (3)9.9. Implement a star field simulation in Implement a star field simulation in

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

10.10.Add a space ship at theAdd a space ship at the bottom of the bottom of the screen.screen.

11.11.Make the ship move leftMake the ship move left or or right right by keyboard keys.by keyboard keys.

64

Page 65: WPF Graphics and Animations

ExercisesExercises12.12. Create a WPF application that showsCreate a WPF application that shows

a circle, filled in orange color with blacka circle, filled in orange color with black borders.borders.

13.13. Create a WPF application that shows the Create a WPF application that shows the text “Hello world” with font family text “Hello world” with font family ConsolasConsolas, size , size 100100, and color , and color blueblue..

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

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

16.16. Create a WPF application that shows all Create a WPF application that shows all fonts in "fonts in "C:\Windows\FontsC:\Windows\Fonts".".

65

Page 66: WPF Graphics and Animations

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

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

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

Use Use ListList and and MarkerStyleMarkerStyle, , StartIndexStartIndex properties. properties.

Page 67: WPF Graphics and Animations

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

the table below:the table below:

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


Recommended