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

  • View

  • Download

Embed Size (px)


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

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

  • 1. WPF Graphics and Animations 2D and 3D Graphics and AnimationsDoncho MinkovTechnical Trainerhttp://www.minkov.itTelerik Software Academyacademy.telerik.com

2. Table of Contents (2)1. Introduction to WPF Graphics2. WPF Drawing Model3. Resolution Independence4. Basic Graphics Objects5. Basic Shapes6. Bitmaps, Images and Effects7. Brushes and Pens8. Transformations9. Animation2 3. Introduction to WPFGraphics 4. Introduction to WPF Graphics Graphical elements can be integrated into any part of user interface Free to mix them with any other kind ofelement Use graphical elements inside controls E.g. put an ellipse inside a button4 5. WPF Graphics ExampleControlszAnd of course you can put graphics intoyour text: 5 6. Introduction to WPFGraphicsLive Demo 7. WPF Drawing Model 8. WPF Drawing Model In WPF we dont 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 drawingsas 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 willautomatically update the display 8 9. WPF Drawing Model Exampleprivate void MainCanvas_MouseLeftButtonDown (object sender, RoutedEventArgs e){ Rectangle r = e.Source as Rectangle; if (r != null) { r.Width += 10; }} 9 10. WPF Drawing ModelLive Demo 11. Resolution Independence,Scaling and Rotation 12. Resolution Independence What is resolution independence? Elements on the screen can be drawn at sizesindependent from the pixel grid Resizing do not affect the image quality WPF resolution independence means that If two monitors are set to their native resolutionand each of them is accurately reporting its DPIsettings to WPF They will display the same WPF window at theexactly the same size 12 13. Resolution Independence (2) WPF is resolution independent, butit 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 resolutions13 14. Scaling and Rotation WPF supports transformationsat 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 15. Scaling and Rotation (2)... The details have become crisper Graphic is clearer Because WPF has rendered the button to lookas good as it can at the specified size15 16. Basic Graphical Objects 17. Shapes, Brushes, and Pens Most of the classes in WPFs drawingtoolkit 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 18. 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 tree18 19. 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 paintonto the screen The Pen class adds more settings Line thickness (1px, 2px, ) Dash patterns (solid, dotted, dashed, ) 19 20. Basic WPF Shapes 21. 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 objects layout space21 22. Rectangle It can be drawneither filled in shape, as an outline, or both filled in and outlined Rectangle doesnt provide any properties for setting its location The location is determined by the container(e.g. Canvas, StackPanel, FlowPanel, )22 23. Rectangle (2) A Rectangle willusually 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 24. 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 25. Line Draws a straightline between two points Controlling the location X1 and Y1 define the start point, and X2 and Y2determine the end pointFooBar 25 26. Ellipses and Lines Live Demo 27. Polyline Draw a connected series of line segments Points property Containing a list of coordinate pairs27 28. Polygon Polygon is very similar to Polyline It has a Points property that works in exactlythe same way as Polylines Polygon alwaysdraws a closed shape 28 29. 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 30. 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 Line30 31. Path (2) GeometryGroup object Create a shape with multiple geometries 31 32. PathLive Demo 33. 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 Bzier curvesand combining shapes 33 34. Arc Segment Example34 35. ArcSegmentLive Demo 36. Bitmaps, Images and Effects 37. 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 38. Image (2) The Image element is able to resize the image The default scaling behavior Use the same scale factor horizontally andvertically Stretch property The image will fill the entire space of itscontainer38 39. ImageSource ImageSource is an abstractbase 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 40. Creating Bitmaps RenderTargetBitmap Create a new bitmap from any visual 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); 40 41. Creating Bitmaps (2) You can choose any resolution you like for the output RenderTargetBitmap lets you builda bitmap out of any combination of WPF visuals It is great if you want to build or modify a bitmap using WPF elements 41 42. 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 43. Bitmap Effects (2) The built-in effects BevelBitmapEffect BitmapEffectGroup BlurBitmapEffect 43 44. Bitmap EffectsLive Demo 45. Brushes and Pens 46. 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 hexadecimaldigits Fill="#8F8" 46 47. LinearGradientBrush The painted area transitions from one color to another The StartPoint and EndPoint properties Indicate where the color transition begins andends These coordinates are relative to the area beingfilled 47 48. LinearGradientBrush (2) Each GradientStop has anOffset property Enables the fill to pass through multiple colors 48 49. 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 50. 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 property 50 51. ImageBrushLive Demo 52. Pen A Pen is always based on a brush Accessed through Stroke property Describes how a shape is outlined Important properties Thickness and DashArray properties52 53. Transformations 54. Transform Classes TranslateTransform displacesthe coordinate system by some amount RotateTransform rotates coordinate system Angle, CenterX, CenterY propertiesIm rotated 35 degrees54 55. Transform Classes ScaleTransform scales the coordinate system up or down ScaleX, ScaleY, CenterX, CenterY properties SkewTransform warpsyour coordinate system by slanting it a number of degrees AngleX, AngleY, CenterX, CenterX MatrixTransform modifies the coordinate system using matrix multiplication Matrix property 55 56. TransformationsLive Demo 57. XAML-Based Animation 58. 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 aninterval of