680 likes | 763 Views
WPF Graphics and Animations. 2 D and 3 D Graphics and Animations. http://schoolacademy.telerik.com. Doncho Minkov. Telerik School Academy. schoolacademy.telerik.com. Technical Trainer. http://www.minkov.it. Table of Contents (2). Introduction to WPF Graphics WPF Drawing Model
E N D
WPF Graphics and Animations 2D and 3D Graphics and Animations http://schoolacademy.telerik.com Doncho Minkov Telerik School Academy schoolacademy.telerik.com Technical Trainer http://www.minkov.it
Table of Contents (2) • Introduction to WPF Graphics • WPF Drawing Model • Resolution Independence • Basic Graphics Objects • Basic Shapes • Bitmaps, Images and Effects • Brushes and Pens • Transformations • Animation
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
WPF Graphics – Example <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>
Introduction to WPF Graphics Live Demo
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
WPF Drawing Model –Example <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; } }
WPF Drawing Model Live Demo
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
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
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.
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 <Button> <Button.LayoutTransform> <ScaleTransform ScaleX="2" ScaleY="2" /> </Button.LayoutTransform> ...<!--The result is--> </Button> <!--without scaling--> <!--with scaling-->
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
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 – takeany visual tree
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, …)
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
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, …) <Canvas> <Rectangle Fill="Yellow" Stroke="Black" Canvas.Left="30" Canvas.Top="10" Width="100" Height="20" /> </Canvas>
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 • RadiusXand RadiusYproperties • Draw a rectangle with rounded corners • RenderTransform property • Transforms a Rectangle relative to its containing panel (rotate, scale, effects, …)
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 <Ellipse Width="100" Height="50" Fill="Yellow" Stroke="Black" /> <!--The result is-->
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 <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>
Ellipses and Lines Live Demo
Polyline • Draw a connected series of line segments • Points property • Containing a list of coordinate pairs <Polyline Stroke="Blue" Points="0,30 10,30 15,0 18,60 23,30 35,30 40,043,60 48,30 160,30" /> <!--The result is-->
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 <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-->
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 <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-->
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
Path (2) • GeometryGroup object • Create a shape with multiple geometries <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>
Path Live Demo
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 • DrawBézier curves and combining shapes
Arc Segment – Example <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>
ArcSegment Live Demo
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 URL <Image Source="http://www.interact-sw.co.uk/images/M3/BackOfM3.jpeg" /> <Image Source="/MyFunnyImage.jpeg" />
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 <Image Source="/MyFunnyImage.jpeg" Stretch="Fill" Opacity="0.5" />
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.
Creating Bitmaps • RenderTargetBitmap • Create a new bitmap from any visual RenderTargetBitmap bmp = newRenderTargetBitmap(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-->
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
Bitmap Effects • BitmapEffects property • Apply a visual effect to the element and all of its children • All of these effects use bitmap processing algorithms <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-->
Bitmap Effects (2) <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> • The built-in effects • BevelBitmapEffect • BitmapEffectGroup • BlurBitmapEffect • …
Bitmap Effects Live Demo
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" <Rectangle Fill="Yellow" Width="100" Height="20" />
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
LinearGradientBrush (2) • Each GradientStop has an Offset property • Enables the fill to pass through multiple colors <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>
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
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