wpf graphics overview
DESCRIPTION
Tutorial downloaded from Microsoft websiteTRANSCRIPT
1
WPF Graphics Overview
WPF Graphics Overview ......................................................................................... Errore. Il segnalibro non è definito.
WPF Graphics Rendering Overview .............................................................................................................................. 4
DrawingVisual Class ................................................................................................................................................ 5
Viewport3DVisual Class ......................................................................................................................................... 5
ContainerVisual Class ............................................................................................................................................. 5
Drawing Content in Visual Objects....................................................................................................................... 5
Control Templates .................................................................................................................................................. 8
Rendering Order ..................................................................................................................................................... 9
Root Visual ............................................................................................................................................................. 10
Relationship to the Logical Tree ......................................................................................................................... 10
Viewing the Visual Tree with XamlPad ............................................................................................................... 11
Profiling Visual Performance ............................................................................................................................... 11
Retained Mode Graphics ..................................................................................................................................... 12
Vector Graphics ..................................................................................................................................................... 13
About Resolution and Device-Independent Graphics ..................................................................................... 14
Hit Testing.............................................................................................................................................................. 16
Enumerating the Visual Tree ............................................................................................................................... 16
Shapes and Basic Drawing in WPF Overview ............................................................................................................ 18
PathGeometry and PathSegments ..................................................................................................................... 21
XAML Abbreviated Syntax ................................................................................................................................... 21
Optimizing Performance: 2D Graphics and Imaging ............................................................................................... 26
BitmapScalingMode ............................................................................................................................................. 28
CachingHint ........................................................................................................................................................... 28
GeometryDrawing Class ............................................................................................................................................... 29
Freezable Features ................................................................................................................................................ 34
Graphics and Multimedia ............................................................................................................................................ 39
2-D Shapes ............................................................................................................................................................ 40
2-D Geometries ..................................................................................................................................................... 41
2-D Effects ............................................................................................................................................................. 41
Images .................................................................................................................................................................... 42
Video and Audio ................................................................................................................................................... 43
Drawing Objects Overview .......................................................................................................................................... 44
Drawings How-to Topics ............................................................................................................................................. 60
2
How to: Apply a GuidelineSet to a Drawing ............................................................................................................. 61
How to: Create a Composite Drawing ....................................................................................................................... 66
How to: Create a GeometryDrawing .......................................................................................................................... 70
How to: Draw an Image Using ImageDrawing ......................................................................................................... 73
How to: Play Media using a VideoDrawing ............................................................................................................... 76
How to: Use a Drawing as an Image Source ............................................................................................................. 78
Geometries .................................................................................................................................................................... 81
Path Markup Syntax ..................................................................................................................................................... 82
A Note about White Space .................................................................................................................................. 82
Syntax ..................................................................................................................................................................... 83
Line Command ...................................................................................................................................................... 84
Horizontal Line Command ................................................................................................................................... 84
Vertical Line Command ........................................................................................................................................ 85
Cubic Bezier Curve Command ............................................................................................................................ 85
Quadratic Bezier Curve Command ..................................................................................................................... 85
Smooth cubic Bezier curve Command ............................................................................................................... 86
Smooth quadratic Bezier curve Command ....................................................................................................... 86
Elliptical Arc Command ........................................................................................................................................ 87
Geometry Overview ...................................................................................................................................................... 89
The Path Shape ..................................................................................................................................................... 89
StreamGeometry ................................................................................................................................................... 99
Path Markup Syntax ............................................................................................................................................. 99
Geometries How-to Topics ........................................................................................................................................ 102
How to: Animate the Size of an ArcSegment .......................................................................................................... 103
How to: Control the Fill of a Composite Shape ...................................................................................................... 106
How to: Create a Combined Geometry ................................................................................................................... 110
How to: Create a Composite Shape ......................................................................................................................... 113
How to: Create a Line Using a LineGeometry ......................................................................................................... 115
How to: Create a LineSegment in a PathGeometry ............................................................................................... 117
How to: Create a Shape by Using a PathGeometry ............................................................................................... 119
How to: Create a Shape Using a StreamGeometry ................................................................................................ 121
How to: Create an Elliptical Arc ................................................................................................................................. 124
How to: Create Multiple Subpaths Within a PathGeometry ................................................................................. 126
How to: Round the Corners of a RectangleGeometry ........................................................................................... 127
Painting with Images, Drawings, and Visuals .......................................................................................................... 129
3
Path Class ..................................................................................................................................................................... 141
StreamGeometry Class ............................................................................................................................................... 171
Freezable Features .............................................................................................................................................. 178
PathGeometry Class ................................................................................................................................................... 182
PathFigureCollection Class ........................................................................................................................................ 192
4
WPF Graphics Rendering Overview .NET Framework 4
This topic provides an overview of the WPF visual layer. It focuses on the role of the Visual class for rendering support
in the WPF model.
This topic contains the following sections.
Role of the Visual Object
How Visual Objects are Used to Build Controls
Visual Tree
Visual Rendering Behavior
VisualTreeHelper Class
Related Topics
Role of the Visual Object
The Visual class is the basic abstraction from which every FrameworkElement object derives. It also serves as the entry
point for writing new controls in WPF, and in many ways can be thought of as the window handle (HWND) in the
Win32 application model.
The Visual object is a core WPF object, whose primary role is to provide rendering support. User interface controls,
such as Button and TextBox, derive from theVisual class, and use it for persisting their rendering data. The Visual object
provides support for:
Output display: Rendering the persisted, serialized drawing content of a visual.
Transformations: Performing transformations on a visual.
Clipping: Providing clipping region support for a visual.
Hit testing: Determining whether a coordinate or geometry is contained within the bounds of a visual.
Bounding box calculations: Determining the bounding rectangle of a visual.
However, the Visual object does not include support for non-rendering features, such as:
Event handling
Layout
Styles
Data binding
Globalization
Visual is exposed as a public abstract class from which child classes must be derived. The following illustration shows
the hierarchy of the visual objects that are exposed in WPF.
Visual class hierarchy
5
DrawingVisual Class
The DrawingVisual is a lightweight drawing class that is used to render shapes, images, or text. This class is considered
lightweight because it does not provide layout or event handling, which improves its runtime performance. For this
reason, drawings are ideal for backgrounds and clip art. The DrawingVisual can be used to create a custom visual
object. For more information, see Using DrawingVisual Objects.
Viewport3DVisual Class
The Viewport3DVisual provides a bridge between 2D Visual and Visual3D objects. The Visual3D class is the base class
for all 3D visual elements. TheViewport3DVisual requires that you define a Camera value and a Viewport value. The
camera allows you to view the scene. The viewport establishes where the projection maps onto the 2D surface. For
more information on 3D in WPF, see 3-D Graphics Overview.
ContainerVisual Class
The ContainerVisual class is used as a container for a collection of Visual objects. The DrawingVisual class derives from
the ContainerVisual class, allowing it to contain a collection of visual objects.
Drawing Content in Visual Objects
A Visual object stores its render data as a vector graphics instruction list. Each item in the instruction list represents
a low-level set of graphics data and associated resources in a serialized format. There are four different types of render
data that can contain drawing content.
Drawing content type Description
Vector graphics Represents vector graphics data, and any
associated Brush and Pen information.
Image Represents an image within a region defined by a Rect.
Glyph Represents a drawing that renders a GlyphRun, which is a sequence of glyphs
from a specified font resource. This is how text is represented.
Video Represents a drawing that renders video.
The DrawingContext allows you to populate a Visual with visual content. When you use a DrawingContext object's
draw commands, you are actually storing a set of render data that will later be used by the graphics system; you are
not drawing to the screen in real-time.
When you create a WPF control, such as a Button, the control implicitly generates render data for drawing itself. For
example, setting the Content property of theButton causes the control to store a rendering representation of a glyph.
A Visual describes its content as one or more Drawing objects contained within a DrawingGroup. A DrawingGroup also
describes opacity masks, transforms, bitmap effects, and other operations that are applied to its
contents. DrawingGroup operations are applied in the following order when content is
rendered:OpacityMask, Opacity, BitmapEffect, ClipGeometry, GuidelineSet, and then Transform.
The following illustration shows the order in which DrawingGroup operations are applied during the rendering
sequence.
Order of DrawingGroup operations
6
For more information, see Drawing Objects Overview.
Drawing Content at the Visual Layer
You never directly instantiate a DrawingContext; you can, however, acquire a drawing context from certain methods,
such as DrawingGroup.Open andDrawingVisual.RenderOpen. The following example retrieves a DrawingContext from
a DrawingVisual and uses it to draw a rectangle.
C#
VB
// Create a DrawingVisual that contains a rectangle. private DrawingVisual CreateDrawingVisualRectangle() { DrawingVisual drawingVisual = new DrawingVisual(); // Retrieve the DrawingContext in order to create new drawing content. DrawingContext drawingContext = drawingVisual.RenderOpen(); // Create a rectangle and draw it in the DrawingContext. Rect rect = new Rect(new System.Windows.Point(160, 100), new System.Windows.Size(320, 80)); drawingContext.DrawRectangle(System.Windows.Media.Brushes.LightBlue, (System.Windows.Media.Pen)null, rect); // Persist the drawing content. drawingContext.Close(); return drawingVisual; }
7
Enumerating Drawing Content at the Visual Layer
In addition to their other uses, Drawing objects also provide an object model for enumerating the contents of a Visual.
Note
When you are enumerating the contents of the visual, you are retrieving Drawing objects, and not the
underlying representation of the render data as a vector graphics instruction list.
The following example uses the GetDrawing method to retrieve the DrawingGroup value of a Visual and enumerate it.
C#
public void RetrieveDrawing(Visual v) { DrawingGroup dGroup = VisualTreeHelper.GetDrawing(v); EnumDrawingGroup(dGroup); } // Enumerate the drawings in the DrawingGroup. public void EnumDrawingGroup(DrawingGroup drawingGroup) { DrawingCollection dc = drawingGroup.Children; // Enumerate the drawings in the DrawingCollection. foreach (Drawing drawing in dc) { // If the drawing is a DrawingGroup, call the function recursively. if (drawing.GetType() == typeof(DrawingGroup)) { EnumDrawingGroup((DrawingGroup)drawing); } else if (drawing.GetType() == typeof(GeometryDrawing)) { // Perform action based on drawing type. } else if (drawing.GetType() == typeof(ImageDrawing)) { // Perform action based on drawing type. } else if (drawing.GetType() == typeof(GlyphRunDrawing)) { // Perform action based on drawing type. } else if (drawing.GetType() == typeof(VideoDrawing)) { // Perform action based on drawing type. } } }
How Visual Objects are Used to Build Controls
Many of the objects in WPF are composed of other visual objects, meaning they can contain varying hierarchies of
descendant objects. Many of the user interface elements in WPF, such as controls, are composed of multiple visual
8
objects, representing different types of rendering elements. For example, the Button control can contain a number of
other objects, including ClassicBorderDecorator, ContentPresenter, and TextBlock.
The following code shows a Button control defined in markup.
XAML
<Button Click="OnClick">OK</Button>
If you were to enumerate the visual objects that comprise the default Button control, you would find
the hierarchy of visual objects illustrated below:
Diagram of visual tree hierarchy
The Button control contains a ClassicBorderDecorator element, which in turn, contains
a ContentPresenter element. The ClassicBorderDecorator element is responsible for drawing a
border and a background for the Button. The ContentPresenter element is responsible for
displaying the contents of the Button. In this case, since you are displaying text,
the ContentPresenter element contains a TextBlock element. The fact that the Button control uses
a ContentPresenter means that the content could be represented by other elements, such as
an Image or a geometry, such as an EllipseGeometry.
Control Templates
The key to the expansion of a control into a hierarchy of controls is the ControlTemplate. A control template specifies
the default visual hierarchy for a control. When you explicitly reference a control, you implicitly reference its visual
hierarchy. You can override the default values for a control template to create a customized visual appearance for a
control. For example, you could modify the background color value of the Button control so that it uses a linear
gradient color value instead of a solid color value. For more information, see Button Styles and Templates.
A user interface element, such as a Button control, contains several vector graphics instruction lists that describe the
entire rendering definition of a control. The following code shows a Button control defined in markup.
XAML
<Button Click="OnClick"> <Image Source="images\greenlight.jpg"></Image> </Button>
If you were to enumerate the visual objects
and vector graphics instruction lists that
comprise the Button control, you would find
the hierarchy of objects illustrated below:
Diagram of visual tree and rendering data
The Button control contains
a ClassicBorderDecorator element, which in
turn, contains a ContentPresenter element.
The ClassicBorderDecorator element is
responsible for drawing all the discrete graphic
elements that make up the border and
background of a button.
9
The ContentPresenter element is responsible for displaying the contents of the Button. In this case, since you are
displaying an image, the ContentPresenter element contains a Image element.
There are a number of points to note about the hierarchy of visual objects and vector graphics instruction lists:
The ordering in the hierarchy represents the rendering order of the drawing information. From the root visual
element, child elements are traversed, left to right, top to bottom. If an element has visual child elements, they
are traversed before the element’s siblings.
Non-leaf node elements in the hierarchy, such as ContentPresenter, are used to contain child elements—they
do not contain instruction lists.
If a visual element contains both a vector graphics instruction list and visual children, the instruction list in the
parent visual element is rendered before drawings in any of the visual child objects.
The items in the vector graphics instruction list are rendered left to right.
Visual Tree
The visual tree contains all visual elements used in an application's user interface. Since a visual element contains
persisted drawing information, you can think of the visual tree as a scene graph, containing all the rendering
information needed to compose the output to the display device. This tree is the accumulation of all visual elements
created directly by the application, whether
in code or in markup. The visual tree also
contains all visual elements created by the
template expansion of elements such as
controls and data objects.
The following code shows
a StackPanel element defined in markup.
XAML
<StackPanel> <Label>User name:</Label> <TextBox /> <Button Click="OnClick">OK</Button> </StackPanel>
If you were to enumerate the visual objects
that comprise the StackPanel element in the
markup example, you would find the
hierarchy of visual objects illustrated below:
Diagram of visual tree hierarchy
Rendering Order
The visual tree determines the rendering order of WPF visual and drawing objects. The order of traversal starts with the
root visual, which is the top-most node in the visual tree. The root visual’s children are then traversed, left to right. If a
visual has children, its children are traversed before the visual’s siblings. This means that the content of a child visual is
rendered in front of the visual's own content.
Diagram of visual tree rendering order
10
Root Visual
The root visual is the top-most element in a visual tree hierarchy. In most applications, the base class of the root
visual is either Window or NavigationWindow. However, if you were hosting visual objects in a Win32 application, the
root visual would be the top-most visual you were hosting in the Win32 window. For more information, see Tutorial:
Hosting Visual Objects in a Win32 Application.
Relationship to the Logical Tree
The logical tree in WPF represents the elements of an application at run time. Although you do not manipulate this
tree directly, this view of the application is useful for understanding property inheritance and event routing. Unlike the
visual tree, the logical tree can represent non-visual data objects, such as ListItem. In many cases, the logical tree maps
very closely to an application's markup definitions. The following code shows a DockPanel element defined in markup.
XAML
<DockPanel> <ListBox> <ListBoxItem>Dog</ListBoxItem> <ListBoxItem>Cat</ListBoxItem> <ListBoxItem>Fish</ListBoxItem> </ListBox> <Button Click="OnClick">OK</Button> </DockPanel>
If you were to enumerate the logical objects that comprise the DockPanel element in the markup example, you would
find the hierarchy of logical objects illustrated below:
Diagram of logical tree
Both the visual tree and logical tree are synchronized with the current set of application elements, reflecting any
addition, deletion, or modification of elements. However, the trees present different views of the application. Unlike
the visual tree, the logical tree does not expand a control's ContentPresenter element. This means there is not a direct
one-to-one correspondence between a logical tree and a visual tree for the same set of objects. In fact, invoking
theLogicalTreeHelper object's GetChildren method and the VisualTreeHelper object's GetChild method using the
same element as a parameter yields differing results.
11
For more information on the logical tree, see Trees in WPF.
Viewing the Visual Tree with XamlPad
The WPF tool, XamlPad, provides an option for viewing and exploring the visual tree that corresponds to the currently
defined XAML content. Click the Show Visual Tree button on the menu bar to display the visual tree. The following
illustrates the expansion of XAML content into visual tree nodes in the Visual Tree Explorer panel of XamlPad:
Visual Tree Explorer panel in XamlPad
Notice how the Label, TextBox, and Button controls each display a separate visual object hierarchy in the Visual Tree
Explorer panel of XamlPad. This is because WPF controls have a ControlTemplate that contains the visual tree of that
control. When you explicitly reference a control, you implicitly reference its visual hierarchy.
Profiling Visual Performance
WPF provides a suite of performance profiling tools that allow you to analyze the run-time behavior of your
application and determine the types of performance optimizations you can apply. The Visual Profiler tool provides a
rich, graphical view of performance data by mapping directly to the application's visual tree. In this screenshot,
the CPU Usage section of the Visual Profiler gives you a precise breakdown of an object's use of WPF services, such as
rendering and layout.
Visual Profiler display output
12
Visual Rendering Behavior
WPF introduces several features that affect the rendering behavior of visual objects: retained mode graphics, vector
graphics, and device independent graphics.
Retained Mode Graphics
One of the keys to understanding the role of the Visual object is to understand the difference between immediate
mode and retained mode graphics systems. A standard Win32 application based on GDI or GDI+ uses an immediate
mode graphics system. This means that the application is responsible for repainting the portion of the client area that
is invalidated, due to an action such as a window being resized, or an object changing its visual appearance.
Diagram of Win32 rendering sequence
In contrast, WPF uses a retained mode system. This means application objects that have a visual appearance define a
set of serialized drawing data. Once the drawing data is defined, the system is responsible thereafter for responding to
all repaint requests for rendering the application objects. Even at run time, you can modify or create application
objects, and still rely on the system for responding to paint requests. The power in a retained mode graphics system is
13
that drawing information is always persisted in a serialized state by the application, but rendering responsibility left to
the system. The following diagram shows how the application relies on WPF for responding to paint requests.
Diagram of WPF rendering sequence
Intelligent Redrawing
One of the biggest benefits in using retained mode graphics is that WPF can efficiently optimize what needs to be
redrawn in the application. Even if you have a complex scene with varying levels of opacity, you generally do not need
to write special-purpose code to optimize redrawing. Compare this with Win32 programming in which you can spend
a great deal of effort in optimizing your application by minimizing the amount of redrawing in the update region.
SeeRedrawing in the Update Region for an example of the type of complexity involved in optimizing redrawing in
Win32 applications.
Vector Graphics
WPF uses vector graphics as its rendering data format. Vector graphics—which include Scalable Vector Graphics
(SVG), Windows metafiles (.wmf), and TrueType fonts—store rendering data and transmit it as a list of instructions that
describe how to recreate an image using graphics primitives. For example, TrueType fonts are outline fonts that
describe a set of lines, curves, and commands, rather than an array of pixels. One of the key benefits of vector graphics
is the ability to scale to any size and resolution.
Unlike vector graphics, bitmap graphics store rendering data as a pixel-by-pixel representation of an image, pre-
rendered for a specific resolution. One of the key differences between bitmap and vector graphic formats is fidelity to
the original source image. For example, when the size of a source image is modified, bitmap graphics systems stretch
the image, whereas vector graphics systems scale the image, preserving the image fidelity.
The following illustration shows a source image that has been resized by 300%. Notice the distortions that appear
when the source image is stretched as a bitmap graphics image rather than scaled as a vector graphics image.
Differences between raster and vector graphics
14
The following markup shows two Path elements defined. The second element uses a ScaleTransform to resize the
drawing instructions of the first element by 300%. Notice that the drawing instructions in the Path elements remain
unchanged.
XAML
<Path Data="M10,100 C 60,0 100,200 150,100 z" Fill="{StaticResource linearGradientBackground}" Stroke="Black" StrokeThickness="2" /> <Path Data="M10,100 C 60,0 100,200 150,100 z" Fill="{StaticResource linearGradientBackground}" Stroke="Black" StrokeThickness="2" > <Path.RenderTransform> <ScaleTransform ScaleX="3.0" ScaleY="3.0" /> </Path.RenderTransform> </Path>
About Resolution and Device-Independent Graphics
There are two system factors that determine the size of text and graphics on your screen: resolution and DPI.
Resolution describes the number of pixels that appear on the screen. As the resolution gets higher, pixels get smaller,
causing graphics and text to appear smaller. A graphic displayed on a monitor set to 1024 x 768 will appear much
smaller when the resolution is changed to 1600 x 1200.
15
The other system setting, DPI, describes the size of a screen inch in pixels. Most Windows systems have a DPI of 96,
which means a screen inch is 96 pixels. Increasing the DPI setting makes the screen inch larger; decreasing the DPI
makes the screen inch smaller. This means that a screen inch isn't the same size as a real-world inch; on most systems,
it's probably not. As you increase the DPI, DPI-aware graphics and text become larger because you've increased the
size of the screen inch. Increasing the DPI can make text easier to read, especially at high resolutions.
Not all applications are DPI-aware: some use hardware pixels as the primary unit of measurement; changing the
system DPI has no effect on these applications. Many other applications use DPI-aware units to describe font sizes, but
use pixels to describe everything else. Making the DPI too small or too large can cause layout problems for these
applications, because the applications' text scales with the system's DPI setting, but the applications' UI does not. This
problem has been eliminated for applications developed using WPF.
WPF supports automatic scaling by using the device independent pixel as its primary unit of measurement, instead of
hardware pixels; graphics and text scale properly without any extra work from the application developer. The following
illustration shows an example of how WPF text and graphics are appear at different DPI settings.
Graphics and text at different DPI settings
VisualTreeHelper Class
16
The VisualTreeHelper class is a static helper class that provides low-level functionality for programming at the visual
object level, which is useful in very specific scenarios, such as developing high-performance custom controls. In most
case, the higher-level WPF framework objects, such as Canvas and TextBlock, offer greater flexibility and ease of use.
Hit Testing
The VisualTreeHelper class provides methods for hit testing on visual objects when the default hit test support does
not meet your needs. You can use theHitTest methods in the VisualTreeHelper class to determine whether a geometry
or point coordinate value is within the boundary of a given object, such as a control or graphic element. For example,
you could use hit testing to determine whether a mouse click within the bounding rectangle of an object falls within
the geometry of a circle You can also choose to override the default implementation of hit testing to perform your
own custom hit test calculations.
For more information on hit testing, see Hit Testing in the Visual Layer.
Enumerating the Visual Tree
The VisualTreeHelper class provides functionality for enumerating the members of a visual tree. To retrieve a parent,
call the GetParent method. To retrieve a child, or direct descendant, of a visual object, call the GetChild method. This
method returns a child Visual of the parent at the specified index.
The following example shows how to enumerate all the descendants of a visual object, which is a technique you might
want to use if you were interested in serializing all the rendering information of a visual object hierarchy.
C#
VB
// Enumerate all the descendants of the visual object. static public void EnumVisual(Visual myVisual) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++) { // Retrieve child visual at specified index value. Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i); // Do processing of the child visual object. // Enumerate children of the child visual object. EnumVisual(childVisual); } }
In most cases, the logical tree is a more useful representation of the elements in a WPF application. Although you do
not modify the logical tree directly, this view of the application is useful for understanding property inheritance and
event routing. Unlike the visual tree, the logical tree can represent non-visual data objects, such as ListItem. For more
information on the logical tree, see Trees in WPF.
The VisualTreeHelper class provides methods for returning the bounding rectangle of visual objects. You can return
the bounding rectangle of a visual object by calling GetContentBounds. You can return the bounding rectangle of all
the descendants of a visual object, including the visual object itself, by callingGetDescendantBounds. The following
code shows how you would calculate the bounding rectangle of a visual object and all its descendants.
C#
VB
17
// Return the bounding rectangle of the parent visual object and all of its descendants. Rect rectBounds = VisualTreeHelper.GetDescendantBounds(parentVisual);
See Also
Reference
Visual
VisualTreeHelper
DrawingVisual
Concepts
Optimizing Performance: 2D Graphics and Imaging
Hit Testing in the Visual Layer
Using DrawingVisual Objects
Tutorial: Hosting Visual Objects in a Win32 Application
Optimizing WPF Application Performance
18
Shapes and Basic Drawing in WPF Overview .NET Framework 4
This topic gives an overview of how to draw with Shape objects. A Shape is a type of UIElement that enables you to
draw a shape to the screen. Because they are UI elements, Shape objects can be used inside Panel elements and most
controls.
Windows Presentation Foundation (WPF) offers several layers of access to graphics and rendering services. At the top
layer, Shape objects are easy to use and provide many useful features, such as layout and participation in the Windows
Presentation Foundation (WPF) event system.
This topic contains the following sections.
Shape Objects
Using Paths and Geometries
Painting Shapes
Stretchable Shapes
Transforming Shapes
Related Topics
Shape Objects
WPF provides a number of ready-to-use Shape objects. All shape objects inherit from the Shape class. Available shape
objects include Ellipse,Line, Path, Polygon, Polyline, and Rectangle. Shape objects share the following common
properties.
Stroke : Describes how the shape's outline is painted.
StrokeThickness : Describes the thickness of the shape's outline.
Fill : Describes how the interior of the shape is painted.
Data properties to specify coordinates and vertices, measured in device-independent pixels.
Because they derive from UIElement, shape objects can be used inside panels and most controls. The Canvas panel is a
particularly good choice for creating complex drawings because it supports absolute positioning of its child objects.
The Line class enables you to draw a line between two points. The following example shows several ways to specify
line coordinates and stroke properties.
XAML <Canvas Height="300" Width="300"> <!-- Draws a diagonal line from (10,10) to (50,50). --> <Line X1="10" Y1="10" X2="50" Y2="50" Stroke="Black" StrokeThickness="4" /> <!-- Draws a diagonal line from (10,10) to (50,50) and moves it 100 pixels to the right. --> <Line X1="10" Y1="10" X2="50" Y2="50" StrokeThickness="4" Canvas.Left="100"> <Line.Stroke>
19
<RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5" RadiusX="0.5" RadiusY="0.5"> <RadialGradientBrush.GradientStops> <GradientStop Color="Red" Offset="0" /> <GradientStop Color="Blue" Offset="0.25" /> </RadialGradientBrush.GradientStops> </RadialGradientBrush> </Line.Stroke> </Line> <!-- Draws a horizontal line from (10,60) to (150,60). --> <Line X1="10" Y1="60" X2="150" Y2="60" Stroke="Black" StrokeThickness="4"/> </Canvas>
C#
C++
VB
// Add a Line Element myLine = new Line(); myLine.Stroke = System.Windows.Media.Brushes.LightSteelBlue; myLine.X1 = 1; myLine.X2 = 50; myLine.Y1 = 1; myLine.Y2 = 50; myLine.HorizontalAlignment = HorizontalAlignment.Left; myLine.VerticalAlignment = VerticalAlignment.Center; myLine.StrokeThickness = 2; myGrid.Children.Add(myLine);
The following image shows the rendered Line.
Although the Line class does provide a Fill property, setting it has no effect because a Line has no area.
Another common shape is the Ellipse. Create an Ellipse by defining the shape's Width and Height properties. To draw a
circle, specify an Ellipse whose Width andHeight values are equal.
XAML
<Ellipse Fill="Yellow" Height="100" Width="200" StrokeThickness="2" Stroke="Black"/>
20
C#
VB
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; namespace SDKSample { public partial class SetBackgroundColorOfShapeExample : Page { public SetBackgroundColorOfShapeExample() { // Create a StackPanel to contain the shape. StackPanel myStackPanel = new StackPanel(); // Create a red Ellipse. Ellipse myEllipse = new Ellipse(); // Create a SolidColorBrush with a red color to fill the // Ellipse with. SolidColorBrush mySolidColorBrush = new SolidColorBrush(); // Describes the brush's color using RGB values. // Each value has a range of 0-255. mySolidColorBrush.Color = Color.FromArgb(255, 255, 255, 0); myEllipse.Fill = mySolidColorBrush; myEllipse.StrokeThickness = 2; myEllipse.Stroke = Brushes.Black; // Set the width and height of the Ellipse. myEllipse.Width = 200; myEllipse.Height = 100; // Add the Ellipse to the StackPanel. myStackPanel.Children.Add(myEllipse); this.Content = myStackPanel; } } }
The following image shows an example of a rendered Ellipse.
Using Paths and Geometries
21
The Path class enables you to draw curves and complex shapes. These curves and shapes are described
using Geometry objects. To use a Path, you create aGeometry and use it to set the Path object's Data property.
There are a variety of Geometry objects to choose from. The LineGeometry, RectangleGeometry,
and EllipseGeometry classes describe relatively simple shapes. To create more complex shapes or create curves, use
a PathGeometry.
PathGeometry and PathSegments
PathGeometry objects are comprised of one or more PathFigure objects; each PathFigure represents a different
"figure" or shape. Each PathFigure is itself comprised of one or more PathSegment objects, each representing a
connected portion of the figure or shape. Segment types include the following:LineSegment, BezierSegment,
and ArcSegment.
In the following example, a Path is used to draw a quadratic Bezier curve.
XAML <Path Stroke="Black" StrokeThickness="1"> <Path.Data> <PathGeometry> <PathGeometry.Figures> <PathFigureCollection> <PathFigure StartPoint="10,100"> <PathFigure.Segments> <PathSegmentCollection> <QuadraticBezierSegment Point1="200,200" Point2="300,100" /> </PathSegmentCollection> </PathFigure.Segments> </PathFigure> </PathFigureCollection> </PathGeometry.Figures> </PathGeometry> </Path.Data> </Path>
The following image shows the rendered shape.
For more information about PathGeometry and the other Geometry classes, see the Geometry Overview.
XAML Abbreviated Syntax
In Extensible Application Markup Language (XAML), you may also use a special abbreviated syntax to describe a Path.
In the following example, abbreviated syntax is used to draw a complex shape.
XAML
<Path Stroke="DarkGoldenRod" StrokeThickness="3" Data="M 100,200 C 100,25 400,350 400,175 H 280" />
22
The following image shows a rendered Path.
The Data attribute string begins with the "moveto" command, indicated by M, which establishes a start point for the
path in the coordinate system of the Canvas.Path data parameters are case-sensitive. The capital M indicates an
absolute location for the new current point. A lowercase m would indicate relative coordinates. The first segment is a
cubic Bezier curve beginning at (100,200) and ending at (400,175), drawn using the two control points (100,25) and
(400,350). This segment is indicated by the C command in the Data attribute string. Again, the capital C indicates an
absolute path; the lowercase c would indicate a relative path.
The second segment begins with an absolute horizontal "lineto" command H, which specifies a line drawn from the
preceding subpath's endpoint (400,175) to a new endpoint (280,175). Because it is a horizontal "lineto" command, the
value specified is an x-coordinate.
For the complete path syntax, see the Data reference and How to: Create a Shape by Using a PathGeometry.
Painting Shapes
Brush objects are used to paint a shape's Stroke and Fill. In the following example, the stroke and fill of an Ellipse are
specified. Note that valid input for brush properties can be either a keyword or hexadecimal color value. For more
information about available color keywords, see properties of the Colors class in
theSystem.Windows.Media namespace.
<Canvas Background="LightGray"> <Ellipse Canvas.Top="50" Canvas.Left="50" Fill="#FFFFFF00" Height="75" Width="75" StrokeThickness="5" Stroke="#FF0000FF"/> </Canvas>
The following image shows the rendered Ellipse.
Alternatively, you can use property element syntax to explicitly create a SolidColorBrush object to paint the shape with
a solid color.
23
<!-- This polygon shape uses pre-defined color values for its Stroke and Fill properties. The SolidColorBrush's Opacity property affects the fill color in this case by making it slightly transparent (opacity of 0.4) so that it blends with any underlying color. --> <Polygon Points="300,200 400,125 400,275 300,200" Stroke="Purple" StrokeThickness="2"> <Polygon.Fill> <SolidColorBrush Color="Blue" Opacity="0.4"/> </Polygon.Fill> </Polygon>
The following illustration shows the rendered shape.
You can also paint a shape's stroke or fill with gradients, images, patterns, and more. For more information, see
the Painting with Solid Colors and Gradients Overview.
Stretchable Shapes
The Line, Path, Polygon, Polyline, and Rectangle classes all have a Stretch property. This property determines how
a Shape object's contents (the shape to be drawn) is stretched to fill the Shape object's layout space. A Shape object's
layout space is the amount of space the Shape is allocated by the layout system, because of either an
explicit Width and Height setting or because of its HorizontalAlignment and VerticalAlignment settings. For additional
information on layout in Windows Presentation Foundation, see Layout System overview.
The Stretch property takes one of the following values:
None : The Shape object's contents are not stretched.
Fill : The Shape object's contents are stretched to fill its layout space. Aspect ratio is not preserved.
Uniform : The Shape object's contents are stretched as much as possible to fill its layout space while preserving
its original aspect ratio.
UniformToFill : The Shape object's contents are stretched to completely fill its layout space while preserving its
original aspect ratio.
Note that, when a Shape object's contents are stretched, the Shape object's outline is painted after the stretching.
In the following example, a Polygon is used to draw a very small triangle from (0,0) to (0,1) to (1,1).
The Polygon object's Width and Height are set to 100, and its stretch property is set to Fill. As a result,
the Polygon object's contents (the triangle) are stretched to fill the larger space.
... <Polygon Points="0,0 0,1 1,1"
24
Fill="Blue" Width="100" Height="100" Stretch="Fill" Stroke="Black" StrokeThickness="2" /> ...
... PointCollection myPointCollection = new PointCollection(); myPointCollection.Add(new Point(0,0)); myPointCollection.Add(new Point(0,1)); myPointCollection.Add(new Point(1,1)); Polygon myPolygon = new Polygon(); myPolygon.Points = myPointCollection; myPolygon.Fill = Brushes.Blue; myPolygon.Width = 100; myPolygon.Height = 100; myPolygon.Stretch = Stretch.Fill; myPolygon.Stroke = Brushes.Black; myPolygon.StrokeThickness = 2; ...
Transforming Shapes
The Transform class provides the means to transform shapes in a two-dimensional plane. The different types of
transformation include rotation (RotateTransform), scale (ScaleTransform), skew (SkewTransform), and translation
(TranslateTransform).
A common transform to apply to a shape is a rotation. To rotate a shape, create a RotateTransform and specify
its Angle. An Angle of 45 rotates the element 45 degrees clockwise; an angle of 90 rotates the element 90 degrees
clockwise; and so on. Set the CenterX and CenterY properties if you want to control the point about which the element
is rotated. These property values are expressed in the coordinate space of the element being
transformed. CenterX and CenterY have default values of zero. Finally, apply the RotateTransform to the element. If
you don't want the transform to affect layout, set the shape's RenderTransformproperty.
In the following example, a RotateTransform is used to rotate a shape 45 degrees about the shape's top left corner
(0,0).
XAML
<!-- Rotates the Polyline 45 degrees about the point (0,0). --> <Polyline Points="25,25 0,50 25,75 50,50 25,25 25,0" Stroke="Blue" StrokeThickness="10" Canvas.Left="75" Canvas.Top="50"> <Polyline.RenderTransform> <RotateTransform CenterX="0" CenterY="0" Angle="45" /> </Polyline.RenderTransform> </Polyline>
In the next example, another shape is rotated 45 degrees, but this time it's rotated about the point (25,50).
XAML <!-- Rotates the Polyline 45 degrees about its center. --> <Polyline Points="25,25 0,50 25,75 50,50 25,25 25,0" Stroke="Blue" StrokeThickness="10"
25
Canvas.Left="75" Canvas.Top="50" RenderTransformOrigin="0.5,0.5"> <Polyline.RenderTransform> <RotateTransform Angle="45" /> </Polyline.RenderTransform> </Polyline>
The following illustration shows the results of applying the two transforms.
In the previous examples, a single transform was applied to each shape object. To apply multiple transforms to a shape
(or any other UI element), use aTransformGroup.
26
Optimizing Performance: 2D Graphics and Imaging .NET Framework 4
WPF provides a wide range of 2D graphics and imaging functionality that can be optimized for your application
requirements. This topic provides information about performance optimization in those areas.
This topic contains the following sections.
Drawing and Shapes
StreamGeometry Objects
DrawingVisual Objects
Images
Related Topics
Drawing and Shapes
WPF provides both Drawing and Shape objects to represent graphical drawing content. However, Drawing objects are
simpler constructs than Shape objects and provide better performance characteristics.
A Shape allows you to draw a graphical shape to the screen. Because they are derived from
the FrameworkElement class, Shape objects can be used inside panels and most controls.
WPF offers several layers of access to graphics and rendering services. At the top layer, Shape objects are easy to use
and provide many useful features, such as layout and event handling. WPF provides a number of ready-to-use shape
objects. All shape objects inherit from the Shape class. Available shape objects
includeEllipse, Line, Path, Polygon, Polyline, and Rectangle.
Drawing objects, on the other hand, do not derive from the FrameworkElement class and provide a lighter-weight
implementation for rendering shapes, images, and text.
There are four types of Drawing objects:
GeometryDrawing Draws a shape.
ImageDrawing Draws an image.
GlyphRunDrawing Draws text.
DrawingGroup Draws other drawings. Use a drawing group to combine other drawings into a single composite
drawing.
The GeometryDrawing object is used to render geometry content. The Geometry class and the concrete classes which
derive from it, such as CombinedGeometry,EllipseGeometry, and PathGeometry, provide a means for rendering 2D
graphics, as well as providing hit-testing and clipping support. Geometry objects can be used to define the region of a
control, for example, or to define the clip region to apply to an image. Geometry objects can be simple regions, such
as rectangles and circles, or composite regions created from two or more geometry objects. More complex geometric
regions can be created by combiningPathSegment-derived objects, such as ArcSegment, BezierSegment,
and QuadraticBezierSegment.
On the surface, the Geometry class and the Shape class are quite similar. Both are used in the rendering of 2D graphics
and both have similar concrete classes which derive from them, for example, EllipseGeometry and Ellipse. However,
there are important differences between these two sets of classes. For one, theGeometry class lacks some of the
functionality of the Shape class, such as the ability to draw itself. To draw a geometry object, another class such as
DrawingContext, Drawing, or a Path (it is worth noting that a Path is a Shape) must be used to perform the drawing
operation. Rendering properties such as fill, stroke, and the stroke thickness are on the class which draws the geometry
object, while a shape object contains these properties. One way to think of this difference is that a geometry object
27
defines a region, a circle for example, while a shape object defines a region, defines how that region is filled and
outlined, and participates in the layout system.
Since Shape objects derive from the FrameworkElement class, using them can add significantly more memory
consumption in your application. If you really do not need the FrameworkElement features for your graphical content,
consider using the lighter-weight Drawing objects.
For more information on Drawing objects, see Drawing Objects Overview.
StreamGeometry Objects
The StreamGeometry object is a light-weight alternative to PathGeometry for creating geometric shapes. Use
a StreamGeometry when you need to describe a complex geometry. StreamGeometry is optimized for handling
many PathGeometry objects and performs better when compared to using many individualPathGeometry objects.
The following example uses attribute syntax to create a triangular StreamGeometry in XAML.
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel> <Path Data="F0 M10,100 L100,100 100,50Z" StrokeThickness="1" Stroke="Black"/> </StackPanel> </Page>
For more information on StreamGeometry objects, see How to: Create a Shape Using a StreamGeometry.
DrawingVisual Objects
The DrawingVisual object is a lightweight drawing class that is used to render shapes, images, or text. This class is
considered lightweight because it does not provide layout or event handling, which improves its performance. For this
reason, drawings are ideal for backgrounds and clip art. For more information, seeUsing DrawingVisual Objects.
Images
WPF imaging provides a significant improvement over the imaging capabilities in previous versions of Windows.
Imaging capabilities, such as displaying a bitmap or using an image on a common control were primarily handled by
the Microsoft Windows Graphics Device Interface (GDI) or Microsoft Windows GDI+ application programming
interface (API). These API provided baseline imaging functionality, but lacked features such as support for codec
extensibility and high fidelity image support. WPF Imaging API have been redesigned to overcome the shortcomings
of GDI and GDI+ and provide a new set of API to display and use images within your applications.
When using images, consider the following recommendations for gaining better performance:
If your application requires you to display thumbnail images, consider creating a reduced-sized version of the
image. By default, WPF loads your image and decodes it to its full size. If you only want a thumbnail version of
the image, WPF unnecessary decodes the image to its full-size and then scales it down to a thumbnail size. To
28
avoid this unnecessary overhead, you can either request WPF to decode the image to a thumbnail size, or
request WPF to load a thumbnail size image.
Always decode the image to desired size and not to the default size. As mentioned above, request WPF to
decode your image to a desired size and not the default full size. You will reduce not only your application's
working set, but execution speed as well.
If possible, combine the images into a single image, such as a film strip composed of multiple images.
For more information, see Imaging Overview.
BitmapScalingMode
When animating the scale of any bitmap, the default high-quality image re-sampling algorithm can sometimes
consume sufficient system resources to cause frame rate degradation, effectively causing animations to stutter. By
setting the BitmapScalingMode property of the RenderOptions object to LowQuality you can create a smoother
animation when scaling a bitmap. LowQuality mode tells the WPF rendering engine to switch from a quality-optimized
algorithm to a speed-optimized algorithm when processing images.
The following example shows how to set the BitmapScalingMode for an image object.
C#
VB
// Set the bitmap scaling mode for the image to render faster. RenderOptions.SetBitmapScalingMode(MyImage, BitmapScalingMode.LowQuality);
CachingHint
By default, WPF does not cache the rendered contents of TileBrush objects, such as DrawingBrush and VisualBrush. In
static scenarios where neither the contents nor use of the TileBrush in the scene is changing, this makes sense, since it
conserves video memory. It does not make as much sense when a TileBrush with static content is used in a non-static
way—for example, when a static DrawingBrush or VisualBrush is mapped to the surface of a rotating 3D object. The
default behavior of WPF is to re-render the entire content of the DrawingBrush or VisualBrush for every frame, even
though the content is unchanging.
By setting the CachingHint property of the RenderOptions object to Cache you can increase performance by using
cached versions of the tiled brush objects.
The CacheInvalidationThresholdMinimum and CacheInvalidationThresholdMaximum property values are relative size
values that determine when the TileBrushobject should be regenerated due to changes in scale. For example, by
setting the CacheInvalidationThresholdMaximum property to 2.0, the cache for theTileBrush only needs to be
regenerated when its size exceeds twice the size of the current cache.
The following example shows how to use the caching hint option for a DrawingBrush.
C#
VB
DrawingBrush drawingBrush = new DrawingBrush(); // Set the caching hint option for the brush. RenderOptions.SetCachingHint(drawingBrush, CachingHint.Cache); // Set the minimum and maximum relative sizes for regenerating the tiled brush. // The tiled brush will be regenerated and re-cached when its size is // 0.5x or 2x of the current cached size. RenderOptions.SetCacheInvalidationThresholdMinimum(drawingBrush, 0.5); RenderOptions.SetCacheInvalidationThresholdMaximum(drawingBrush, 2.0);
29
GeometryDrawing Class .NET Framework 4
Draws a Geometry using the specified Brush and Pen.
Inheritance Hierarchy
System.Object
System.Windows.Threading.DispatcherObject
System.Windows.DependencyObject
System.Windows.Freezable
System.Windows.Media.Animation.Animatable
System.Windows.Media.Drawing
System.Windows.Media.GeometryDrawing
Namespace: System.Windows.Media
Assembly: PresentationCore (in PresentationCore.dll)
XMLNS for XAML: http://schemas.microsoft.com/winfx/2006/xaml/presentation,
http://schemas.microsoft.com/netfx/2007/xaml/presentation
Syntax
C#
C++
F#
VB
public sealed class GeometryDrawing : Drawing
XAML Object Element Usage
<GeometryDrawing .../>
The GeometryDrawing type exposes the following members.
Constructors
Name Description
GeometryDrawing() Initializes a new instance of the GeometryDrawing class.
GeometryDrawing(Brush, Pen, Geometry)
Initializes a new instance of the GeometryDrawing class with the specified Brush, Pen, and Geometry.
Top
30
Properties
Name Description
Bounds Gets the axis-aligned bounds of the drawing's contents. (Inherited from Drawing.)
Brush Gets or sets the Brush used to fill the interior of the shape described by this GeometryDrawing.
CanFreeze Gets a value that indicates whether the object can be made unmodifiable. (Inherited from Freezable.)
DependencyObjectType Gets the DependencyObjectType that wraps the CLR type of this instance. (Inherited from DependencyObject.)
Dispatcher Gets the Dispatcher this DispatcherObject is associated with. (Inherited from DispatcherObject.)
Geometry Gets or sets the Geometry that describes the shape of this GeometryDrawing.
HasAnimatedProperties Gets a value that indicates whether one or more AnimationClock objects is associated with any of this object's dependency properties. (Inherited from Animatable.)
IsFrozen Gets a value that indicates whether the object is currently modifiable. (Inherited from Freezable.)
IsSealed Gets a value that indicates whether this instance is currently sealed (read-only). (Inherited from DependencyObject.)
Pen Gets or sets the Pen used to stroke this GeometryDrawing.
Top
Methods
Name Description
ApplyAnimationClock(DependencyProperty, AnimationClock)
Applies an AnimationClock to the specified DependencyProperty. If the property is already animated, the SnapshotAndReplace handoff behavior is used. (Inherited from Animatable.)
ApplyAnimationClock(DependencyProperty, AnimationClock, HandoffBehavior)
Applies an AnimationClock to the specified DependencyProperty. If the property is already animated, the specified HandoffBehavior is used. (Inherited from Animatable.)
BeginAnimation(DependencyProperty, Applies an animation to the specified DependencyProperty.
31
AnimationTimeline) The animation is started when the next frame is rendered. If the specified property is already animated, theSnapshotAndReplace handoff behavior is used. (Inherited from Animatable.)
BeginAnimation(DependencyProperty, AnimationTimeline, HandoffBehavior)
Applies an animation to the specified DependencyProperty. The animation is started when the next frame is rendered. If the specified property is already animated, the specifiedHandoffBehavior is used. (Inherited from Animatable.)
CheckAccess Determines whether the calling thread has access to this DispatcherObject. (Inherited fromDispatcherObject.)
ClearValue(DependencyProperty) Clears the local value of a property. The property to be cleared is specified by aDependencyProperty identifier. (Inherited from DependencyObject.)
ClearValue(DependencyPropertyKey) Clears the local value of a read-only property. The property to be cleared is specified by aDependencyPropertyKey. (Inherited from DependencyObject.)
Clone Creates a modifiable clone of this GeometryDrawing, making deep copies of this object's values. When copying dependency properties, this method copies resource references and data bindings (but they might no longer resolve) but not animations or their current values.
CloneCore Makes the instance a clone (deep copy) of the specified Freezable using base (non-animated) property values. (Inherited from Freezable.)
CloneCurrentValue Creates a modifiable clone of this GeometryDrawing object, making deep copies of this object's current values. Resource references, data bindings, and animations are not copied, but their current values are.
CloneCurrentValueCore Makes the instance a modifiable clone (deep copy) of the specified Freezable using current property values. (Inherited from Freezable.)
CoerceValue Coerces the value of the specified dependency property. This is accomplished by invoking any CoerceValueCallback function specified in property metadata for the dependency property as it exists on the calling DependencyObject. (Inherited from DependencyObject.)
CreateInstance Initializes a new instance of the Freezable class. (Inherited from Freezable.)
CreateInstanceCore When implemented in a derived class, creates a new instance of the Freezable derived class.(Inherited from Freezable.)
Equals Determines whether a provided DependencyObject is equivalent to the currentDependencyObject. (Inherited from DependencyObject.)
32
Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Freeze() Makes the current object unmodifiable and sets its IsFrozen property to true. (Inherited fromFreezable.)
FreezeCore Makes this Animatable object unmodifiable or determines whether it can be made unmodifiable. (Inherited from Animatable.)
GetAnimationBaseValue Returns the non-animated value of the specified DependencyProperty. (Inherited fromAnimatable.)
GetAsFrozen Creates a frozen copy of the Freezable, using base (non-animated) property values. Because the copy is frozen, any frozen sub-objects are copied by reference. (Inherited fromFreezable.)
GetAsFrozenCore Makes the instance a frozen clone of the specified Freezable using base (non-animated) property values. (Inherited from Freezable.)
GetCurrentValueAsFrozen Creates a frozen copy of the Freezable using current property values. Because the copy is frozen, any frozen sub-objects are copied by reference. (Inherited from Freezable.)
GetCurrentValueAsFrozenCore Makes the current instance a frozen clone of the specified Freezable. If the object has animated dependency properties, their current animated values are copied. (Inherited fromFreezable.)
GetHashCode Gets a hash code for this DependencyObject. (Inherited from DependencyObject.)
GetLocalValueEnumerator Creates a specialized enumerator for determining which dependency properties have locally set values on this DependencyObject. (Inherited from DependencyObject.)
GetType Gets the Type of the current instance. (Inherited from Object.)
GetValue Returns the current effective value of a dependency property on this instance of aDependencyObject. (Inherited from DependencyObject.)
InvalidateProperty Re-evaluates the effective value for the specified dependency property (Inherited fromDependencyObject.)
MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
OnChanged Called when the current Freezable object is modified. (Inherited from Freezable.)
OnFreezablePropertyChanged(DependencyObject, Ensures that appropriate context pointers are established for
33
DependencyObject) a DependencyObjectType data member that has just been set. (Inherited from Freezable.)
OnFreezablePropertyChanged(DependencyObject, DependencyObject, DependencyProperty)
This member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code. (Inherited from Freezable.)
OnPropertyChanged Overrides the DependencyObject implementation of OnPropertyChanged to also invoke anyChanged handlers in response to a changing dependency property of type Freezable.(Inherited from Freezable.)
ReadLocalValue Returns the local value of a dependency property, if it exists. (Inherited fromDependencyObject.)
ReadPreamble Ensures that the Freezable is being accessed from a valid thread. Inheritors of Freezable must call this method at the beginning of any API that reads data members that are not dependency properties. (Inherited from Freezable.)
SetCurrentValue Sets the value of a dependency property without changing its value source. (Inherited fromDependencyObject.)
SetValue(DependencyProperty, Object) Sets the local value of a dependency property, specified by its dependency property identifier. (Inherited from DependencyObject.)
SetValue(DependencyPropertyKey, Object) Sets the local value of a read-only dependency property, specified by theDependencyPropertyKey identifier of the dependency property. (Inherited fromDependencyObject.)
ShouldSerializeProperty Returns a value that indicates whether serialization processes should serialize the value for the provided dependency property. (Inherited from DependencyObject.)
ToString Returns a string that represents the current object. (Inherited from Object.)
VerifyAccess Enforces that the calling thread has access to this DispatcherObject. (Inherited fromDispatcherObject.)
WritePostscript Raises the Changed event for the Freezable and invokes its OnChanged method. Classes that derive from Freezable should call this method at the end of any API that modifies class members that are not stored as dependency properties. (Inherited from Freezable.)
WritePreamble Verifies that the Freezable is not frozen and that it is being accessed from a valid threading context. Freezable inheritors should call this method at the beginning of any API that writes to data members that are not dependency properties. (Inherited from Freezable.)
Top
Events
34
Name Description
Changed Occurs when the Freezable or an object it contains is modified. (Inherited from Freezable.)
Top
Fields
Name Description
BrushProperty Identifies the Brush dependency property.
GeometryProperty Identifies the Geometry dependency property.
PenProperty Identifies the Pen dependency property.
Top
Remarks
Use the GeometryDrawing class with a DrawingBrush to paint an object with a shape, with an DrawingImage to
create clip art, or with a DrawingVisual.
Freezable Features
A GeometryDrawing is a type of Freezable object and therefore can be frozen to improve performance. For
information about Freezable features, such as freezing and cloning, see the Freezable Objects Overview.
Examples
This example shows how to create and display a GeometryDrawing. A GeometryDrawing enables you to create
shape with a fill and an outline by associating aPen and a Brush with a Geometry. The Geometry describes the shape's
structure, the Brush describes the shape's fill, and the Pen describes the shape's outline.
The following example uses a GeometryDrawing to render a shape. The shape is described by a GeometryGroup and
two EllipseGeometry objects. The shape's interior is painted with a LinearGradientBrush and its outline is drawn with
a Black Pen. The GeometryDrawing is displayed using an ImageDrawing and an Imageelement.
C#
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes;
35
namespace SDKSample { public class GeometryDrawingExample : Page { public GeometryDrawingExample() { // // Create the Geometry to draw. // GeometryGroup ellipses = new GeometryGroup(); ellipses.Children.Add( new EllipseGeometry(new Point(50,50), 45, 20) ); ellipses.Children.Add( new EllipseGeometry(new Point(50, 50), 20, 45) ); // // Create a GeometryDrawing. // GeometryDrawing aGeometryDrawing = new GeometryDrawing(); aGeometryDrawing.Geometry = ellipses; // Paint the drawing with a gradient. aGeometryDrawing.Brush = new LinearGradientBrush( Colors.Blue, Color.FromRgb(204,204,255), new Point(0,0), new Point(1,1)); // Outline the drawing with a solid color. aGeometryDrawing.Pen = new Pen(Brushes.Black, 10); // // Use a DrawingImage and an Image control // to display the drawing. // DrawingImage geometryImage = new DrawingImage(aGeometryDrawing); // Freeze the DrawingImage for performance benefits. geometryImage.Freeze(); Image anImage = new Image(); anImage.Source = geometryImage; anImage.Stretch = Stretch.None; anImage.HorizontalAlignment = HorizontalAlignment.Left; // // Place the image inside a border and // add it to the page. // Border exampleBorder = new Border(); exampleBorder.Child = anImage; exampleBorder.BorderBrush = Brushes.Gray; exampleBorder.BorderThickness = new Thickness(1); exampleBorder.HorizontalAlignment = HorizontalAlignment.Left; exampleBorder.VerticalAlignment = VerticalAlignment.Top; exampleBorder.Margin = new Thickness(10); this.Margin = new Thickness(20); this.Background = Brushes.White; this.Content = exampleBorder;
36
} } }
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="PresentationOptions" Margin="20" Background="White"> <Border BorderBrush="Gray" BorderThickness="1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10"> <Image Stretch="None" HorizontalAlignment="Left"> <Image.Source> <DrawingImage PresentationOptions:Freeze="True"> <DrawingImage.Drawing> <GeometryDrawing> <GeometryDrawing.Geometry> <!-- Create a composite shape. --> <GeometryGroup> <EllipseGeometry Center="50,50" RadiusX="45" RadiusY="20" /> <EllipseGeometry Center="50,50" RadiusX="20" RadiusY="45" /> </GeometryGroup> </GeometryDrawing.Geometry> <GeometryDrawing.Brush> <!-- Paint the drawing with a gradient. --> <LinearGradientBrush> <GradientStop Offset="0.0" Color="Blue" /> <GradientStop Offset="1.0" Color="#CCCCFF" /> </LinearGradientBrush> </GeometryDrawing.Brush> <GeometryDrawing.Pen> <!-- Outline the drawing with a solid color. --> <Pen Thickness="10" Brush="Black" /> </GeometryDrawing.Pen> </GeometryDrawing> </DrawingImage.Drawing> </DrawingImage> </Image.Source> </Image> </Border> </Page>
The following illustration shows the resulting GeometryDrawing.
37
To create more complex drawings, you can combine multiple drawing objects into a single composite drawing using
a DrawingGroup.
More Code
How to: Paint an Area with a Drawing
This example shows how to paint an area with a drawing. To paint an area with a drawing, you use a DrawingBrush and one or moreDrawing objects. The following example uses a DrawingBrush to paint an object with a drawing of two ellipses.
Version Information
.NET Framework
Supported in: 4, 3.5, 3.0
.NET Framework Client Profile
Supported in: 4, 3.5 SP1
Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows
Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET
Framework System Requirements.
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not
guaranteed to be thread safe.
See Also
Reference
System.Windows.Media Namespace
DrawingImage
DrawingBrush
Geometry
38
Other Resources
Drawing Objects Overview
Geometry Overview
How to: Make a Freezable Read-Only
39
Graphics and Multimedia .NET Framework 4
Windows Presentation Foundation (WPF) provides support for multimedia, vector graphics, animation, and content
composition, making it easy for developers to build interesting user interfaces and content. Using Microsoft Visual
Studio, you can create vector graphics or complex animations and integrate media into your applications.
This topic introduces the graphics, animation, and media features of WPF, which enable you to add graphics, transition
effects, sound, and video to your applications.
Note
Using WPF types in a Windows service is strongly discouraged. If you attempt to use WPF types in a
Windows service, the service may not work as expected.
This topic contains the following sections.
What's New with Graphics and Multimedia in WPF 4
Graphics and Rendering
3-D Rendering
Animation
Media
Related Topics
What's New with Graphics and Multimedia in WPF 4
Several changes have been made related to graphics and animations.
Layout Rounding
When an object edge falls in the middle of a pixel device, the DPI-independent graphics system can create
rendering artifacts, such as blurry or semi-transparent edges. Previous versions of WPF included pixel snapping
to help handle this case. Silverlight 2 introduced layout rounding, which is another way to move elements so
that edges fall on whole pixel boundaries. WPF now supports layout rounding with
the UseLayoutRounding attached property onFrameworkElement.
Cached Composition
By using the new BitmapCache and BitmapCacheBrush classes, you can cache a complex part of the visual tree
as a bitmap and greatly improve rendering time. The bitmap remains responsive to user input, such as mouse
clicks, and you can paint it onto other elements just like any brush.
Pixel Shader 3 Support
WPF 4 builds on top of the ShaderEffect support introduced in WPF 3.5 SP1 by allowing applications to write
effects by using Pixel Shader (PS) version 3.0. The PS 3.0 shader model is more sophisticated than PS 2.0, which
allows for even more effects on supported hardware.
Easing Functions
You can enhance animations with easing functions, which give you additional control over the behavior of
animations. For example, you can apply anElasticEase to an animation to give the animation a springy behavior.
For more information, see the easing types in the System.Windows.Media.Animationnamespace.
40
Graphics and Rendering
WPF includes support for high quality 2-D graphics. The functionality includes brushes, geometries, images, shapes
and transformations. For more information, see Graphics. The rendering of graphical elements is based on
the Visual class. The structure of visual objects on the screen is described by the visual tree. For more information,
see WPF Graphics Rendering Overview.
2-D Shapes
WPF provides a library of commonly used, vector-drawn 2-D shapes, such as rectangles and ellipses, which the
following illustration shows.
These intrinsic WPF shapes are not just shapes: they are programmable elements that implement many of the features
that you expect from most common controls, which include keyboard and mouse input. The following example shows
how to handle the MouseUp event raised by clicking an Ellipse element.
XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="Window1" > <Ellipse Fill="LightBlue" MouseUp="ellipseButton_MouseUp" /> </Window>
C#
VB
public partial class Window1 : Window { void ellipseButton_MouseUp(object sender, MouseButtonEventArgs e) { MessageBox.Show("You clicked the ellipse!"); } }
The following illustration shows the output for the preceding
XAML markup and code-behind.
For more information, see Shapes and Basic Drawing in WPF
Overview. For an introductory sample, see Shape Elements
Sample.
41
2-D Geometries
When the 2-D shapes that WPF provides are not sufficient, you can use WPF support for geometries and paths to
create your own. The following illustration shows how you can use geometries to create shapes, as a drawing brush,
and to clip other WPF elements.
For more information, see Geometry Overview. For an introductory sample, see Geometries Sample.
2-D Effects
WPF provides a library of 2-D classes that you can use to create a variety of effects. The 2-D rendering capability of
WPF provides the ability to paint UI elements that have gradients, bitmaps, drawings, and videos; and to manipulate
them by using rotation, scaling, and skewing. The following illustration gives an example of the many effects you can
achieve by using WPF brushes.
For more information, see WPF Brushes Overview. For an introductory sample, see Brushes Sample.
3-D Rendering
WPF provides a set of 3-D rendering capabilities that integrate with 2-D graphics support in WPF in order for you to
create more exciting layout, UI, and data visualization. At one end of the spectrum, WPF enables you to render 2-D
images onto the surfaces of 3-D shapes, which the following illustration demonstrates.
42
For more information, see 3-D Graphics Overview. For an introductory sample, see 3-D Solids Sample.
Animation
Use animation to make controls and elements grow, shake, spin, and fade; and to create interesting page transitions,
and more. Because WPF enables you to animate most properties, not only can you animate most WPF objects, you can
also use WPF to animate custom objects that you create.
For more information, see Animation Overview. For an introductory sample, see Animation Example Gallery.
Media
Images, video, and audio are media-rich ways of conveying information and user experiences.
Images
43
Images, which include icons, backgrounds, and even parts of animations, are a core part of most applications. Because
you frequently need to use images, WPF exposes the ability to work with them in a variety of ways. The following
illustration shows just one of those ways.
For more information, see Imaging Overview.
Video and Audio
A core feature of the graphics capabilities of WPF is to provide native support for working with multimedia, which
includes video and audio. The following example shows how to insert a media player into an application.
XAML
<MediaElement Source="media\numbers.wmv" Width="450" Height="250" />
MediaElement is capable of playing both video and audio, and is extensible enough to allow the easy creation of
custom UIs.
For more information, see the Multimedia Overview.
See Also
Reference
System.Windows.Media
System.Windows.Media.Animation
System.Windows.Media.Media3D
Concepts
Optimizing Performance: 2D Graphics and Imaging
Shapes and Basic Drawing in WPF Overview
Painting with Solid Colors and Gradients Overview
Painting with Images, Drawings, and Visuals
Other Resources
Animation and Timing
3-D Graphics
Multimedia
44
Drawing Objects Overview .NET Framework 4
This topic introduces Drawing objects and describes how to use them to efficiently draw shapes, bitmaps, text, and
media. Use Drawing objects when you create clip art, paint with a DrawingBrush, or use Visual objects.
This topic contains the following sections.
What Is a Drawing Object?
Draw a Shape
Draw an Image
Play Media (Code Only)
Draw Text
Composite Drawings
Display a Drawing as an Image
Paint an Object with a Drawing
Render a Drawing with a Visual
DrawingContext Objects
Enumerate the Contents of a Visual
Related Topics
What Is a Drawing Object?
A Drawing object describes visible content, such as a shape, bitmap, video, or a line of text. Different types of drawings
describe different types of content. The following is a list of the different types of drawing objects.
GeometryDrawing – Draws a shape.
ImageDrawing – Draws an image.
GlyphRunDrawing – Draws text.
VideoDrawing – Plays an audio or video file.
DrawingGroup – Draws other drawings. Use a drawing group to combine other drawings into a single
composite drawing.
Drawing objects are versatile; there are many ways you can use a Drawing object.
You can display it as an image by using a DrawingImage and an Image control.
You can use it with a DrawingBrush to paint an object, such as the Background of a Page.
You can use it to describe the appearance of a DrawingVisual.
You can use it to enumerate the contents of a Visual.
WPF provides other types of objects that are capable of drawing shapes, bitmaps, text, and media. For example, you
can also use Shape objects to draw shapes, and the MediaElement control provides another way to add video to your
application. So when should you use Drawing objects? When you can sacrifice framework level features to gain
performance benefits or when you need Freezable features. Because Drawing objects lack support for Layout System,
input, and focus, they provide performance benefits that make them ideal for describing backgrounds, clip art, and for
low-level drawing with Visual objects.
Because they are a type Freezable object, Drawing objects gain several special features, which include the following:
they can be declared as resources, shared among multiple objects, made read-only to improve performance, cloned,
and made thread-safe. For more information about the different features provided byFreezable objects, see
the Freezable Objects Overview.
Draw a Shape
45
To draw a shape, you use a GeometryDrawing. A geometry drawing's Geometry property describes the shape to draw,
its Brush property describes how the interior of the shape should be painted, and its Pen property describes how its
outline should be drawn.
The following example uses a GeometryDrawing to draw a shape. The shape is described by a GeometryGroup and
two EllipseGeometry objects. The shape's interior is painted with a LinearGradientBrush and its outline is drawn with
a Black Pen.
This example creates the following GeometryDrawing.
A GeometryDrawing
C#
// // Create the Geometry to draw. // GeometryGroup ellipses = new GeometryGroup(); ellipses.Children.Add( new EllipseGeometry(new Point(50,50), 45, 20) ); ellipses.Children.Add( new EllipseGeometry(new Point(50, 50), 20, 45) ); // // Create a GeometryDrawing. // GeometryDrawing aGeometryDrawing = new GeometryDrawing(); aGeometryDrawing.Geometry = ellipses; // Paint the drawing with a gradient. aGeometryDrawing.Brush = new LinearGradientBrush( Colors.Blue, Color.FromRgb(204,204,255), new Point(0,0), new Point(1,1)); // Outline the drawing with a solid color. aGeometryDrawing.Pen = new Pen(Brushes.Black, 10);
XAML
<GeometryDrawing> <GeometryDrawing.Geometry> <!-- Create a composite shape. --> <GeometryGroup> <EllipseGeometry Center="50,50" RadiusX="45" RadiusY="20" /> <EllipseGeometry Center="50,50" RadiusX="20" RadiusY="45" /> </GeometryGroup>
46
</GeometryDrawing.Geometry> <GeometryDrawing.Brush> <!-- Paint the drawing with a gradient. --> <LinearGradientBrush> <GradientStop Offset="0.0" Color="Blue" /> <GradientStop Offset="1.0" Color="#CCCCFF" /> </LinearGradientBrush> </GeometryDrawing.Brush> <GeometryDrawing.Pen> <!-- Outline the drawing with a solid color. --> <Pen Thickness="10" Brush="Black" /> </GeometryDrawing.Pen> </GeometryDrawing>
For the complete example, see How to: Create a GeometryDrawing.
Other Geometry classes, such as PathGeometry enable you to create more complex shapes by creating curves and arcs.
For more information about Geometryobjects, see the Geometry Overview.
For more information about other ways to draw shapes that don't use Drawing objects, see Shapes and Basic Drawing
in WPF Overview.
Draw an Image
To draw an image, you use an ImageDrawing. An ImageDrawing object's ImageSource property describes the image
to draw, and its Rect property defines the region where the image is drawn.
The following example draws an image into a rectangle located at (75,75) that is 100 by 100 pixel. The following
illustration shows the ImageDrawing created by the example. A gray border was added to show the bounds of
the ImageDrawing.
A 100 by 100 ImageDrawing
C#
// Create a 100 by 100 image with an upper-left point of (75,75). ImageDrawing bigKiwi = new ImageDrawing(); bigKiwi.Rect = new Rect(75, 75, 100, 100); bigKiwi.ImageSource = new BitmapImage( new Uri(@"sampleImages\kiwi.png", UriKind.Relative));
XAML
47
<!-- The Rect property specifies that the image only fill a 100 by 100 rectangular area. --> <ImageDrawing Rect="75,75,100,100" ImageSource="sampleImages\kiwi.png"/>
For more information about images, see the Imaging Overview.
Play Media (Code Only)
Note
Although you can declare a VideoDrawing in Extensible Application Markup Language (XAML), you can only load and play its media using
code. To play video in Extensible Application Markup Language (XAML), use a MediaElement instead.
To play an audio or video file, you use a VideoDrawing and a MediaPlayer. There are two ways to load and play media.
The first is to use a MediaPlayer and aVideoDrawing by themselves, and the second way is to create your
own MediaTimeline to use with the MediaPlayer and VideoDrawing.
Note
When distributing media with your application, you cannot use a media file as a project resource, like you would an image. In your project
file, you must instead set the media type to Content and set CopyToOutputDirectory to PreserveNewest or Always.
To play media without creating your own MediaTimeline, you perform the following steps.
1. Create a MediaPlayer object.
C#
MediaPlayer player = new MediaPlayer();
2. Use the Open method to load the media file.
C#
player.Open(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative));
3. Create a VideoDrawing.
C#
VideoDrawing aVideoDrawing = new VideoDrawing();
4. Specify the size and location to draw the media by setting the Rect property of the VideoDrawing.
C#
aVideoDrawing.Rect = new Rect(0, 0, 100, 100);
5. Set the Player property of the VideoDrawing with the MediaPlayer you created.
C#
48
aVideoDrawing.Player = player;
6. Use the Play method of the MediaPlayer to start playing the media.
C#
// Play the video once. player.Play();
The following example uses a VideoDrawing and a MediaPlayer to play a video file once.
C# // // Create a VideoDrawing. // MediaPlayer player = new MediaPlayer(); player.Open(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative)); VideoDrawing aVideoDrawing = new VideoDrawing(); aVideoDrawing.Rect = new Rect(0, 0, 100, 100); aVideoDrawing.Player = player; // Play the video once. player.Play();
To gain additional timing control over the media, use a MediaTimeline with
the MediaPlayer and VideoDrawing objects. The MediaTimeline enables you to specify whether the video should
repeat. To use a MediaTimeline with a VideoDrawing, you perform the following steps:
1. Declare the MediaTimeline and set its timing behaviors.
C#
// Create a MediaTimeline. MediaTimeline mTimeline = new MediaTimeline(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative)); // Set the timeline to repeat. mTimeline.RepeatBehavior = RepeatBehavior.Forever;
2. Create a MediaClock from the MediaTimeline.
C#
// Create a clock from the MediaTimeline. MediaClock mClock = mTimeline.CreateClock();
3. Create a MediaPlayer and use the MediaClock to set its Clock property.
C#
MediaPlayer repeatingVideoDrawingPlayer = new MediaPlayer(); repeatingVideoDrawingPlayer.Clock = mClock;
49
4. Create a VideoDrawing and assign the MediaPlayer to the Player property of the VideoDrawing.
C#
VideoDrawing repeatingVideoDrawing = new VideoDrawing(); repeatingVideoDrawing.Rect = new Rect(150, 0, 100, 100); repeatingVideoDrawing.Player = repeatingVideoDrawingPlayer;
The following example uses a MediaTimeline with a MediaPlayer and a VideoDrawing to play a video repeatedly.
C#
// // Create a VideoDrawing that repeats. // // Create a MediaTimeline. MediaTimeline mTimeline = new MediaTimeline(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative)); // Set the timeline to repeat. mTimeline.RepeatBehavior = RepeatBehavior.Forever; // Create a clock from the MediaTimeline. MediaClock mClock = mTimeline.CreateClock(); MediaPlayer repeatingVideoDrawingPlayer = new MediaPlayer(); repeatingVideoDrawingPlayer.Clock = mClock; VideoDrawing repeatingVideoDrawing = new VideoDrawing(); repeatingVideoDrawing.Rect = new Rect(150, 0, 100, 100); repeatingVideoDrawing.Player = repeatingVideoDrawingPlayer;
Note that, when you use a MediaTimeline, you use the interactive ClockController returned from
the Controller property of the MediaClock to control media playback instead of the interactive methods
of MediaPlayer.
Draw Text
To draw text, you use a GlyphRunDrawing and a GlyphRun. The following example uses a GlyphRunDrawing to draw
the text "Hello World".
C#
GlyphRun theGlyphRun = new GlyphRun( new GlyphTypeface(new Uri(@"C:\WINDOWS\Fonts\TIMES.TTF")), 0, false, 13.333333333333334, new ushort[]{43, 72, 79, 79, 82, 3, 58, 82, 85, 79, 71}, new Point(0, 12.29), new double[]{ 9.62666666666667, 7.41333333333333, 2.96, 2.96, 7.41333333333333, 3.70666666666667, 12.5866666666667, 7.41333333333333, 4.44, 2.96, 7.41333333333333}, null, null, null, null,
50
null, null ); GlyphRunDrawing gDrawing = new GlyphRunDrawing(Brushes.Black, theGlyphRun);
XAML <GlyphRunDrawing ForegroundBrush="Black"> <GlyphRunDrawing.GlyphRun> <GlyphRun CaretStops="{x:Null}" ClusterMap="{x:Null}" IsSideways="False" GlyphOffsets="{x:Null}" GlyphIndices="43 72 79 79 82 3 58 82 85 79 71" BaselineOrigin="0,12.29" FontRenderingEmSize="13.333333333333334" DeviceFontName="{x:Null}" AdvanceWidths="9.62666666666667 7.41333333333333 2.96 2.96 7.41333333333333 3.70666666666667 12.5866666666667 7.41333333333333 4.44 2.96 7.41333333333333" BidiLevel="0"> <GlyphRun.GlyphTypeface> <GlyphTypeface FontUri="C:\WINDOWS\Fonts\TIMES.TTF" /> </GlyphRun.GlyphTypeface> </GlyphRun> </GlyphRunDrawing.GlyphRun> </GlyphRunDrawing>
A GlyphRun is a low-level object intended for use with fixed-format document presentation and print scenarios. A
simpler way to draw text to the screen is to use a Label or a TextBlock. For more information about GlyphRun, see
the Introduction to the GlyphRun Object and Glyphs Element overview.
Composite Drawings
A DrawingGroup enables you to combine multiple drawings into a single composite drawing. By using
a DrawingGroup, you can combine shapes, images, and text into a single Drawing object.
The following example uses a DrawingGroup to combine two GeometryDrawing objects and an ImageDrawing object.
This example produces the following output.
A composite drawing
C#
51
// // Create three drawings. // GeometryDrawing ellipseDrawing = new GeometryDrawing( new SolidColorBrush(Color.FromArgb(102, 181, 243, 20)), new Pen(Brushes.Black, 4), new EllipseGeometry(new Point(50,50), 50, 50) ); ImageDrawing kiwiPictureDrawing = new ImageDrawing( new BitmapImage(new Uri(@"sampleImages\kiwi.png", UriKind.Relative)), new Rect(50,50,100,100)); GeometryDrawing ellipseDrawing2 = new GeometryDrawing( new SolidColorBrush(Color.FromArgb(102,181,243,20)), new Pen(Brushes.Black, 4), new EllipseGeometry(new Point(150, 150), 50, 50) ); // Create a DrawingGroup to contain the drawings. DrawingGroup aDrawingGroup = new DrawingGroup(); aDrawingGroup.Children.Add(ellipseDrawing); aDrawingGroup.Children.Add(kiwiPictureDrawing); aDrawingGroup.Children.Add(ellipseDrawing2);
XAML
<DrawingGroup> <GeometryDrawing Brush="#66B5F314"> <GeometryDrawing.Geometry> <EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50"/> </GeometryDrawing.Geometry> <GeometryDrawing.Pen> <Pen Brush="Black" Thickness="4" /> </GeometryDrawing.Pen> </GeometryDrawing> <ImageDrawing ImageSource="sampleImages\kiwi.png" Rect="50,50,100,100"/> <GeometryDrawing Brush="#66B5F314"> <GeometryDrawing.Geometry> <EllipseGeometry Center="150,150" RadiusX="50" RadiusY="50"/> </GeometryDrawing.Geometry> <GeometryDrawing.Pen> <Pen Brush="Black" Thickness="4" /> </GeometryDrawing.Pen> </GeometryDrawing> </DrawingGroup>
A DrawingGroup also enables you to apply opacity masks, transforms, bitmap effects, and other operations to its
contents. DrawingGroup operations are applied in the following
order: OpacityMask, Opacity, BitmapEffect, ClipGeometry, GuidelineSet, and then Transform.
The following illustration shows the order in which DrawingGroup operations are applied.
Order of DrawingGroup operations
52
The following table describes the properties you can use to manipulate a DrawingGroup object's contents.
Property Description Illustration
OpacityMask Alters the opacity of selected
portions of
the DrawingGroup contents. For
an example, see How to: Control
the Opacity of a Drawing.
Opacity Uniformly changes the opacity
of the DrawingGroup contents.
Use this property to make
a Drawing transparent or
partially transparent. For an
example, seeHow to: Apply an
Opacity Mask to a Drawing.
53
BitmapEffect Applies a BitmapEffect to
the DrawingGroup contents. For
an example, see How to: Apply a
BitmapEffect to a Drawing.
ClipGeometry Clips
the DrawingGroup contents to a
region you describe using
a Geometry. For an example,
see How to: Clip a Drawing .
GuidelineSet Snaps device independent pixels
to device pixels along the
specified guidelines. This
property is useful for ensuring
that finely detailed graphics
render sharply on low-DPI
displays. For an example,
see How to: Apply a
GuidelineSet to a Drawing.
Transform Transforms
the DrawingGroup contents. For
an example, see How to: Apply a
Transform to a Drawing.
Display a Drawing as an Image
To display a Drawing with an Image control, use a DrawingImage as the Image control's Source and set
the DrawingImage object's DrawingImage.Drawingproperty to the drawing you want to display.
The following example uses a DrawingImage and an Image control to display a GeometryDrawing. This example
produces the following output.
A DrawingImage
54
C#
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace SDKSample { public class DrawingImageExample : Page { public DrawingImageExample() { // // Create the Geometry to draw. // GeometryGroup ellipses = new GeometryGroup(); ellipses.Children.Add( new EllipseGeometry(new Point(50,50), 45, 20) ); ellipses.Children.Add( new EllipseGeometry(new Point(50, 50), 20, 45) ); // // Create a GeometryDrawing. // GeometryDrawing aGeometryDrawing = new GeometryDrawing(); aGeometryDrawing.Geometry = ellipses; // Paint the drawing with a gradient. aGeometryDrawing.Brush = new LinearGradientBrush( Colors.Blue, Color.FromRgb(204,204,255), new Point(0,0), new Point(1,1)); // Outline the drawing with a solid color. aGeometryDrawing.Pen = new Pen(Brushes.Black, 10); // // Use a DrawingImage and an Image control // to display the drawing. // DrawingImage geometryImage = new DrawingImage(aGeometryDrawing); // Freeze the DrawingImage for performance benefits. geometryImage.Freeze(); Image anImage = new Image(); anImage.Source = geometryImage; anImage.HorizontalAlignment = HorizontalAlignment.Left;
55
// // Place the image inside a border and // add it to the page. // Border exampleBorder = new Border(); exampleBorder.Child = anImage; exampleBorder.BorderBrush = Brushes.Gray; exampleBorder.BorderThickness = new Thickness(1); exampleBorder.HorizontalAlignment = HorizontalAlignment.Left; exampleBorder.VerticalAlignment = VerticalAlignment.Top; exampleBorder.Margin = new Thickness(10); this.Margin = new Thickness(20); this.Background = Brushes.White; this.Content = exampleBorder; } } }
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="PresentationOptions" Background="White" Margin="20"> <Border BorderBrush="Gray" BorderThickness="1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10"> <!-- This image uses a Drawing object for its source. --> <Image> <Image.Source> <DrawingImage PresentationOptions:Freeze="True"> <DrawingImage.Drawing> <GeometryDrawing> <GeometryDrawing.Geometry> <GeometryGroup> <EllipseGeometry Center="50,50" RadiusX="45" RadiusY="20" /> <EllipseGeometry Center="50,50" RadiusX="20" RadiusY="45" /> </GeometryGroup> </GeometryDrawing.Geometry> <GeometryDrawing.Brush> <LinearGradientBrush> <GradientStop Offset="0.0" Color="Blue" /> <GradientStop Offset="1.0" Color="#CCCCFF" /> </LinearGradientBrush> </GeometryDrawing.Brush> <GeometryDrawing.Pen> <Pen Thickness="10" Brush="Black" /> </GeometryDrawing.Pen> </GeometryDrawing> </DrawingImage.Drawing> </DrawingImage> </Image.Source> </Image> </Border>
56
</Page>
Paint an Object with a Drawing
A DrawingBrush is a type of brush that paints an area with a drawing object. You can use it to paint just about any
graphical object with a drawing. The Drawingproperty of a DrawingBrush describes its Drawing. To render
a Drawing with a DrawingBrush, add it to the brush using the brush's Drawing property and use the brush to paint a
graphical object, such as a control or panel.
The following examples uses a DrawingBrush to paint the Fill of a Rectangle with a pattern created from
a GeometryDrawing. This example produces the following output.
A GeometryDrawing used with a DrawingBrush
C#
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace SDKSample { public class DrawingBrushExample : Page { public DrawingBrushExample() { // // Create the Geometry to draw. // GeometryGroup ellipses = new GeometryGroup(); ellipses.Children.Add( new EllipseGeometry(new Point(50,50), 45, 20) ); ellipses.Children.Add( new EllipseGeometry(new Point(50, 50), 20, 45) ); // // Create a GeometryDrawing. // GeometryDrawing aGeometryDrawing = new GeometryDrawing(); aGeometryDrawing.Geometry = ellipses; // Paint the drawing with a gradient. aGeometryDrawing.Brush = new LinearGradientBrush( Colors.Blue,
57
Color.FromRgb(204,204,255), new Point(0,0), new Point(1,1)); // Outline the drawing with a solid color. aGeometryDrawing.Pen = new Pen(Brushes.Black, 10); DrawingBrush patternBrush = new DrawingBrush(aGeometryDrawing); patternBrush.Viewport = new Rect(0, 0, 0.25, 0.25); patternBrush.TileMode = TileMode.Tile; patternBrush.Freeze(); // // Create an object to paint. // Rectangle paintedRectangle = new Rectangle(); paintedRectangle.Width = 100; paintedRectangle.Height = 100; paintedRectangle.Fill = patternBrush; // // Place the image inside a border and // add it to the page. // Border exampleBorder = new Border(); exampleBorder.Child = paintedRectangle; exampleBorder.BorderBrush = Brushes.Gray; exampleBorder.BorderThickness = new Thickness(1); exampleBorder.HorizontalAlignment = HorizontalAlignment.Left; exampleBorder.VerticalAlignment = VerticalAlignment.Top; exampleBorder.Margin = new Thickness(10); this.Margin = new Thickness(20); this.Background = Brushes.White; this.Content = exampleBorder; } } }
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="PresentationOptions" Margin="20" Background="White"> <Border BorderBrush="Gray" BorderThickness="1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10"> <Rectangle Width="100" Height="100"> <Rectangle.Fill> <DrawingBrush PresentationOptions:Freeze="True" Viewport="0,0,0.25,0.25" TileMode="Tile"> <DrawingBrush.Drawing> <GeometryDrawing> <GeometryDrawing.Geometry> <GeometryGroup> <EllipseGeometry Center="50,50" RadiusX="45" RadiusY="20" /> <EllipseGeometry Center="50,50" RadiusX="20" RadiusY="45" />
58
</GeometryGroup> </GeometryDrawing.Geometry> <GeometryDrawing.Brush> <LinearGradientBrush> <GradientStop Offset="0.0" Color="Blue" /> <GradientStop Offset="1.0" Color="#CCCCFF" /> </LinearGradientBrush> </GeometryDrawing.Brush> <GeometryDrawing.Pen> <Pen Thickness="10" Brush="Black" /> </GeometryDrawing.Pen> </GeometryDrawing> </DrawingBrush.Drawing> </DrawingBrush> </Rectangle.Fill> </Rectangle> </Border> </Page>
The DrawingBrush class provides a variety of options for stretching and tiling its content. For more information
about DrawingBrush, see the Painting with Images, Drawings, and Visuals overview.
Render a Drawing with a Visual
A DrawingVisual is a type of visual object designed to render a drawing. Working directly at the visual layer is an
option for developers who want to build a highly customized graphical environment, and is not described in this
overview. For more information, see the Using DrawingVisual Objects overview.
DrawingContext Objects
The DrawingContext class enables you to populate a Visual or a Drawing with visual content. Many such lower-level
graphics objects use a DrawingContextbecause it describes graphical content very efficiently.
Although the DrawingContext draw methods appear similar to the draw methods of the System.Drawing.Graphics type,
they are actually very different.DrawingContext is used with a retained mode graphics system, while
the System.Drawing.Graphics type is used with an immediate mode graphics system. When you use
a DrawingContext object's draw commands, you are actually storing a set of rendering instructions (although the exact
storage mechanism depends on the type of object that supplies the DrawingContext) that will later be used by the
graphics system; you are not drawing to the screen in real-time. For more information about how the Windows
Presentation Foundation (WPF) graphics system works, see the WPF Graphics Rendering Overview.
You never directly instantiate a DrawingContext; you can, however, acquire a drawing context from certain methods,
such as DrawingGroup.Open andDrawingVisual.RenderOpen.
Enumerate the Contents of a Visual
In addition to their other uses, Drawing objects also provide an object model for enumerating the contents of a Visual.
The following example uses the GetDrawing method to retrieve the DrawingGroup value of a Visual and enumerate it.
59
C#
public void RetrieveDrawing(Visual v) { DrawingGroup dGroup = VisualTreeHelper.GetDrawing(v); EnumDrawingGroup(dGroup); } // Enumerate the drawings in the DrawingGroup. public void EnumDrawingGroup(DrawingGroup drawingGroup) { DrawingCollection dc = drawingGroup.Children; // Enumerate the drawings in the DrawingCollection. foreach (Drawing drawing in dc) { // If the drawing is a DrawingGroup, call the function recursively. if (drawing.GetType() == typeof(DrawingGroup)) { EnumDrawingGroup((DrawingGroup)drawing); } else if (drawing.GetType() == typeof(GeometryDrawing)) { // Perform action based on drawing type. } else if (drawing.GetType() == typeof(ImageDrawing)) { // Perform action based on drawing type. } else if (drawing.GetType() == typeof(GlyphRunDrawing)) { // Perform action based on drawing type. } else if (drawing.GetType() == typeof(VideoDrawing)) { // Perform action based on drawing type. } } }
See Also
Reference
Drawing
DrawingGroup
Concepts
Optimizing Performance: 2D Graphics and Imaging
Painting with Images, Drawings, and Visuals
Geometry Overview
Shapes and Basic Drawing in WPF Overview
WPF Graphics Rendering Overview
Freezable Objects Overview
Other Resources
Drawings How-to Topics
60
Drawings How-to Topics .NET Framework 4
The topics in this section describe how to use Drawing objects to draw shapes, images, or text.
In This Section
How to: Apply a GuidelineSet to a Drawing
How to: Create a Composite Drawing
How to: Create a GeometryDrawing
How to: Draw an Image Using ImageDrawing
How to: Play Media using a VideoDrawing
How to: Use a Drawing as an Image Source
See Also
Reference
Drawing
Concepts
WPF Graphics Rendering Overview
Shapes and Basic Drawing in WPF Overview
Graphics and Multimedia
61
How to: Apply a GuidelineSet to a Drawing .NET Framework 4
This example shows how to apply a GuidelineSet to a DrawingGroup.
The DrawingGroup class is the only type of Drawing that has a GuidelineSet property. To apply a GuidelineSet to
another type of Drawing, add it to aDrawingGroup and then apply the GuidelineSet to your DrawingGroup.
Example
The following example creates two DrawingGroup objects that are almost identical; the only difference is: the
second DrawingGroup has a GuidelineSet and the first does not.
The following illustration shows the output from the example. Because the rendering difference between the
two DrawingGroup objects is so subtle, portions of the drawings are enlarged.
C#
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace SDKSample { /// <summary> /// This example shows how to apply a GuidelineSet to /// a drawing. /// </summary> public class DrawingGroupGuidelineSetExample : Page { public DrawingGroupGuidelineSetExample() {
62
// // Create a DrawingGroup // that has no guideline set // GeometryDrawing drawing1 = new GeometryDrawing( Brushes.Black, null, new RectangleGeometry(new Rect(0,20,30,80)) ); GeometryGroup whiteRectangles = new GeometryGroup(); whiteRectangles.Children.Add(new RectangleGeometry(new Rect(5.5, 25, 20, 20))); whiteRectangles.Children.Add(new RectangleGeometry(new Rect(5.5, 50, 20, 20))); whiteRectangles.Children.Add(new RectangleGeometry(new Rect(5.5, 75, 20, 20))); GeometryDrawing drawing2 = new GeometryDrawing( Brushes.White, null, whiteRectangles ); // Create a DrawingGroup DrawingGroup drawingGroupWithoutGuidelines = new DrawingGroup(); drawingGroupWithoutGuidelines.Children.Add(drawing1); drawingGroupWithoutGuidelines.Children.Add(drawing2); // Use an Image control and a DrawingImage to display the drawing. DrawingImage drawingImage01 = new DrawingImage(drawingGroupWithoutGuidelines); // Freeze the DrawingImage for performance benefits. drawingImage01.Freeze(); Image image01 = new Image(); image01.Source = drawingImage01; image01.Stretch = Stretch.None; image01.HorizontalAlignment = HorizontalAlignment.Left; image01.Margin = new Thickness(10); // // Create another DrawingGroup and apply a blur effect to it. // // Create a clone of the first DrawingGroup. DrawingGroup drawingGroupWithGuidelines = drawingGroupWithoutGuidelines.Clone(); // Create a guideline set. GuidelineSet guidelines = new GuidelineSet(); guidelines.GuidelinesX.Add(5.5); guidelines.GuidelinesX.Add(25.5); guidelines.GuidelinesY.Add(25); guidelines.GuidelinesY.Add(50); guidelines.GuidelinesY.Add(75); // Apply it to the drawing group. drawingGroupWithGuidelines.GuidelineSet = guidelines; // Use another Image control and DrawingImage // to display the drawing. DrawingImage drawingImage02 = new DrawingImage(drawingGroupWithGuidelines); // Freeze the DrawingImage for performance benefits. drawingImage02.Freeze();
63
Image image02 = new Image(); image02.Source = drawingImage02; image02.Stretch = Stretch.None; image02.HorizontalAlignment = HorizontalAlignment.Left; image02.Margin = new Thickness(50, 10, 10, 10); StackPanel mainPanel = new StackPanel(); mainPanel.Orientation = Orientation.Horizontal; mainPanel.HorizontalAlignment = HorizontalAlignment.Left; mainPanel.Margin = new Thickness(20); mainPanel.Children.Add(image01); mainPanel.Children.Add(image02); // // Use a DrawingBrush to create a grid background. // GeometryDrawing backgroundRectangleDrawing = new GeometryDrawing( Brushes.White, null, new RectangleGeometry(new Rect(0,0,1,1)) ); PolyLineSegment backgroundLine1 = new PolyLineSegment(); backgroundLine1.Points.Add(new Point(1, 0)); backgroundLine1.Points.Add(new Point(1, 0.1)); backgroundLine1.Points.Add(new Point(0, 0.1)); PathFigure line1Figure = new PathFigure(); line1Figure.Segments.Add(backgroundLine1); PathGeometry backgroundLine1Geometry = new PathGeometry(); backgroundLine1Geometry.Figures.Add(line1Figure); GeometryDrawing backgroundLineDrawing1 = new GeometryDrawing( new SolidColorBrush(Color.FromArgb(255,204,204,255)), null, backgroundLine1Geometry ); PolyLineSegment backgroundLine2 = new PolyLineSegment(); backgroundLine2.Points.Add(new Point(0, 1)); backgroundLine2.Points.Add(new Point(0.1, 1)); backgroundLine2.Points.Add(new Point(0.1, 0)); PathFigure line2Figure = new PathFigure(); line2Figure.Segments.Add(backgroundLine2); PathGeometry backgroundLine2Geometry = new PathGeometry(); backgroundLine2Geometry.Figures.Add(line2Figure); GeometryDrawing backgroundLineDrawing2 = new GeometryDrawing( new SolidColorBrush(Color.FromArgb(255, 204, 204, 255)), null, backgroundLine2Geometry ); DrawingGroup backgroundGroup = new DrawingGroup(); backgroundGroup.Children.Add(backgroundRectangleDrawing); backgroundGroup.Children.Add(backgroundLineDrawing1); backgroundGroup.Children.Add(backgroundLineDrawing2); DrawingBrush gridPatternBrush = new DrawingBrush(backgroundGroup); gridPatternBrush.Viewport = new Rect(0, 0, 10, 10); gridPatternBrush.ViewportUnits = BrushMappingMode.Absolute; gridPatternBrush.TileMode = TileMode.Tile; gridPatternBrush.Freeze(); Border mainBorder = new Border(); mainBorder.Background = gridPatternBrush; mainBorder.BorderThickness = new Thickness(1); mainBorder.BorderBrush = Brushes.Gray; mainBorder.HorizontalAlignment = HorizontalAlignment.Left;
64
mainBorder.VerticalAlignment = VerticalAlignment.Top; mainBorder.Margin = new Thickness(20); mainBorder.Child = mainPanel; // // Add the items to the page. // this.Content = mainBorder; this.Background = Brushes.White; } } }
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="PresentationOptions"> <Border BorderThickness="1" BorderBrush="Gray" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="20"> <StackPanel Margin="20" Orientation="Horizontal"> <Image Stretch="None" Margin="10"> <Image.Source> <DrawingImage PresentationOptions:Freeze="True"> <DrawingImage.Drawing> <!-- This DrawingGroup has no GuidelineSet. --> <DrawingGroup> <GeometryDrawing Brush="Black"> <GeometryDrawing.Geometry> <RectangleGeometry Rect="0,20,30,80" /> </GeometryDrawing.Geometry> </GeometryDrawing> <GeometryDrawing Brush="White"> <GeometryDrawing.Geometry> <GeometryGroup> <RectangleGeometry Rect="5.5,25, 20,20" /> <RectangleGeometry Rect="5.5,50, 20,20" /> <RectangleGeometry Rect="5.5,75, 20,20" /> </GeometryGroup> </GeometryDrawing.Geometry> </GeometryDrawing> </DrawingGroup> </DrawingImage.Drawing> </DrawingImage> </Image.Source> </Image> <Image Stretch="None" Margin="50,10,10,10"> <Image.Source> <DrawingImage PresentationOptions:Freeze="True"> <DrawingImage.Drawing> <!-- This DrawingGroup has a GuidelineSet. --> <DrawingGroup>
65
<GeometryDrawing Brush="Black"> <GeometryDrawing.Geometry> <RectangleGeometry Rect="0,20,30,80" /> </GeometryDrawing.Geometry> </GeometryDrawing> <GeometryDrawing Brush="White"> <GeometryDrawing.Geometry> <GeometryGroup> <RectangleGeometry Rect="5.5,25, 20,20" /> <RectangleGeometry Rect="5.5,50, 20,20" /> <RectangleGeometry Rect="5.5,75, 20,20" /> </GeometryGroup> </GeometryDrawing.Geometry> </GeometryDrawing> <DrawingGroup.GuidelineSet> <!-- The GuidelineSet --> <GuidelineSet GuidelinesX="5.5,25.5" GuidelinesY="25,50,75" /> </DrawingGroup.GuidelineSet> </DrawingGroup> </DrawingImage.Drawing> </DrawingImage> </Image.Source> </Image> </StackPanel> <Border.Background> <DrawingBrush Viewport="0,0,10,10" ViewportUnits="Absolute" TileMode="Tile" PresentationOptions:Freeze="True"> <DrawingBrush.Drawing> <DrawingGroup> <GeometryDrawing Brush="White"> <GeometryDrawing.Geometry> <RectangleGeometry Rect="0,0,1,1" /> </GeometryDrawing.Geometry> </GeometryDrawing> <GeometryDrawing Geometry="M0,0 L1,0 1,0.1, 0,0.1Z " Brush="#CCCCFF" /> <GeometryDrawing Geometry="M0,0 L0,1 0.1,1, 0.1,0Z" Brush="#CCCCFF" /> </DrawingGroup> </DrawingBrush.Drawing> </DrawingBrush> </Border.Background> </Border> </Page>
See Also
Reference
DrawingGroup
GuidelineSet
Concepts
Drawing Objects Overview
66
How to: Create a Composite Drawing .NET Framework 4
This example shows how to use a DrawingGroup to create complex drawings by combining multiple Drawing objects
into a single composite drawing.
Example
The following example uses a DrawingGroup to create a composite drawing from
the GeometryDrawing and ImageDrawing objects. The following illustration shows the output that this example
produces.
A composite drawing that is created by using DrawingGroup
Note the gray border, which shows the bounds of the drawing.
C#
// // Create three drawings. // GeometryDrawing ellipseDrawing = new GeometryDrawing( new SolidColorBrush(Color.FromArgb(102, 181, 243, 20)), new Pen(Brushes.Black, 4), new EllipseGeometry(new Point(50,50), 50, 50)); ImageDrawing kiwiPictureDrawing = new ImageDrawing( new BitmapImage(new Uri(@"sampleImages\kiwi.png", UriKind.Relative)), new Rect(50,50,100,100)); GeometryDrawing ellipseDrawing2 = new GeometryDrawing( new SolidColorBrush(Color.FromArgb(102,181,243,20)), new Pen(Brushes.Black, 4), new EllipseGeometry(new Point(150, 150), 50, 50)); // Create a DrawingGroup to contain the drawings. DrawingGroup aDrawingGroup = new DrawingGroup(); aDrawingGroup.Children.Add(ellipseDrawing); aDrawingGroup.Children.Add(kiwiPictureDrawing); aDrawingGroup.Children.Add(ellipseDrawing2);
67
XAML
<DrawingGroup> <GeometryDrawing Brush="#66B5F314"> <GeometryDrawing.Geometry> <EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50"/> </GeometryDrawing.Geometry> <GeometryDrawing.Pen> <Pen Brush="Black" Thickness="4" /> </GeometryDrawing.Pen> </GeometryDrawing> <ImageDrawing ImageSource="sampleImages\kiwi.png" Rect="50,50,100,100"/> <GeometryDrawing Brush="#66B5F314"> <GeometryDrawing.Geometry> <EllipseGeometry Center="150,150" RadiusX="50" RadiusY="50"/> </GeometryDrawing.Geometry> <GeometryDrawing.Pen> <Pen Brush="Black" Thickness="4" /> </GeometryDrawing.Pen> </GeometryDrawing> </DrawingGroup>
You can use a DrawingGroup to apply a Transform, Opacity setting, OpacityMask, BitmapEffect, ClipGeometry,
or GuidelineSet to the drawings it contains. Because a DrawingGroup is also a Drawing, it can contain
other DrawingGroup objects.
The following example is similar to the preceding example, except that it uses additional DrawingGroup objects to
apply bitmap effects and an opacity mask to some of its drawings. The following illustration shows the output that this
example produces.
Composite drawing that has multiple DrawingGroup objects
Note the gray border, which shows the bounds of the drawing.
C#
// Create a DrawingGroup. DrawingGroup mainGroup = new DrawingGroup(); // // Create a GeometryDrawing // GeometryDrawing ellipseDrawing = new GeometryDrawing( new SolidColorBrush(Color.FromArgb(102, 181, 243, 20)), new Pen(Brushes.Black, 4),
68
new EllipseGeometry(new Point(50, 50), 50, 50) ); // // Use a DrawingGroup to apply a blur // bitmap effect to the drawing. // DrawingGroup blurGroup = new DrawingGroup(); blurGroup.Children.Add(ellipseDrawing); BlurBitmapEffect blurEffect = new BlurBitmapEffect(); blurEffect.Radius = 5; blurGroup.BitmapEffect = blurEffect; // Add the DrawingGroup to the main DrawingGroup. mainGroup.Children.Add(blurGroup); // // Create an ImageDrawing. // ImageDrawing kiwiPictureDrawing = new ImageDrawing( new BitmapImage(new Uri(@"sampleImages\kiwi.png", UriKind.Relative)), new Rect(50, 50, 100, 100)); // // Use a DrawingGroup to apply an opacity mask // and a bevel. // DrawingGroup maskedAndBeveledGroup = new DrawingGroup(); maskedAndBeveledGroup.Children.Add(kiwiPictureDrawing); // Create an opacity mask. RadialGradientBrush rgBrush =new RadialGradientBrush(); rgBrush.GradientStops.Add(new GradientStop(Color.FromArgb(0,0,0,0), 0.55)); rgBrush.GradientStops.Add(new GradientStop(Color.FromArgb(255,0,0,0), 0.65)); rgBrush.GradientStops.Add(new GradientStop(Color.FromArgb(0,0,0,0), 0.75)); rgBrush.GradientStops.Add(new GradientStop(Color.FromArgb(255,0,0,0), 0.80)); rgBrush.GradientStops.Add(new GradientStop(Color.FromArgb(0,0,0,0), 0.90)); rgBrush.GradientStops.Add(new GradientStop(Color.FromArgb(255,0,0,0), 1.0)); maskedAndBeveledGroup.OpacityMask = rgBrush; // Apply a bevel. maskedAndBeveledGroup.BitmapEffect = new BevelBitmapEffect(); // Add the DrawingGroup to the main group. mainGroup.Children.Add(maskedAndBeveledGroup); // // Create another GeometryDrawing. // GeometryDrawing ellipseDrawing2 = new GeometryDrawing( new SolidColorBrush(Color.FromArgb(102, 181, 243, 20)), new Pen(Brushes.Black, 4), new EllipseGeometry(new Point(150, 150), 50, 50) ); // Add the DrawingGroup to the main group. mainGroup.Children.Add(ellipseDrawing2);
XAML
<DrawingGroup>
69
<DrawingGroup> <GeometryDrawing Brush="#66B5F314"> <GeometryDrawing.Geometry> <EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50"/> </GeometryDrawing.Geometry> <GeometryDrawing.Pen> <Pen Brush="Black" Thickness="4" /> </GeometryDrawing.Pen> </GeometryDrawing> <DrawingGroup.BitmapEffect> <BlurBitmapEffect Radius="5" /> </DrawingGroup.BitmapEffect> </DrawingGroup> <DrawingGroup> <ImageDrawing ImageSource="sampleImages\kiwi.png" Rect="50,50,100,100"/> <DrawingGroup.BitmapEffect> <BevelBitmapEffect /> </DrawingGroup.BitmapEffect> <DrawingGroup.OpacityMask> <RadialGradientBrush> <GradientStop Offset="0.55" Color="#00000000" /> <GradientStop Offset="0.65" Color="#FF000000" /> <GradientStop Offset="0.75" Color="#00000000" /> <GradientStop Offset="0.80" Color="#FF000000" /> <GradientStop Offset="0.90" Color="#00000000" /> <GradientStop Offset="1.0" Color="#FF000000" /> </RadialGradientBrush> </DrawingGroup.OpacityMask> </DrawingGroup> <GeometryDrawing Brush="#66B5F314"> <GeometryDrawing.Geometry> <EllipseGeometry Center="150,150" RadiusX="50" RadiusY="50"/> </GeometryDrawing.Geometry> <GeometryDrawing.Pen> <Pen Brush="Black" Thickness="4" /> </GeometryDrawing.Pen> </GeometryDrawing> </DrawingGroup>
For more information about Drawing objects, see Drawing Objects Overview.
See Also
Reference
BitmapEffect
Transform
OpacityMask
Opacity
ClipGeometry
GuidelineSet
Concepts
Drawing Objects Overview
70
How to: Create a GeometryDrawing .NET Framework 4
This example shows how to create and display a GeometryDrawing. A GeometryDrawing enables you to create shape
with a fill and an outline by associating a Penand a Brush with a Geometry. The Geometry describes the shape's
structure, the Brush describes the shape's fill, and the Pen describes the shape's outline.
Example
The following example uses a GeometryDrawing to render a shape. The shape is described by a GeometryGroup and
two EllipseGeometry objects. The shape's interior is painted with a LinearGradientBrush and its outline is drawn with
a Black Pen. The GeometryDrawing is displayed using an ImageDrawing and an Imageelement.
C#
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace SDKSample { public class GeometryDrawingExample : Page { public GeometryDrawingExample() { // // Create the Geometry to draw. // GeometryGroup ellipses = new GeometryGroup(); ellipses.Children.Add( new EllipseGeometry(new Point(50,50), 45, 20) ); ellipses.Children.Add( new EllipseGeometry(new Point(50, 50), 20, 45) ); // // Create a GeometryDrawing. // GeometryDrawing aGeometryDrawing = new GeometryDrawing(); aGeometryDrawing.Geometry = ellipses; // Paint the drawing with a gradient. aGeometryDrawing.Brush = new LinearGradientBrush( Colors.Blue, Color.FromRgb(204,204,255), new Point(0,0), new Point(1,1)); // Outline the drawing with a solid color. aGeometryDrawing.Pen = new Pen(Brushes.Black, 10);
71
// // Use a DrawingImage and an Image control // to display the drawing. // DrawingImage geometryImage = new DrawingImage(aGeometryDrawing); // Freeze the DrawingImage for performance benefits. geometryImage.Freeze(); Image anImage = new Image(); anImage.Source = geometryImage; anImage.Stretch = Stretch.None; anImage.HorizontalAlignment = HorizontalAlignment.Left; // // Place the image inside a border and // add it to the page. // Border exampleBorder = new Border(); exampleBorder.Child = anImage; exampleBorder.BorderBrush = Brushes.Gray; exampleBorder.BorderThickness = new Thickness(1); exampleBorder.HorizontalAlignment = HorizontalAlignment.Left; exampleBorder.VerticalAlignment = VerticalAlignment.Top; exampleBorder.Margin = new Thickness(10); this.Margin = new Thickness(20); this.Background = Brushes.White; this.Content = exampleBorder; } } }
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="PresentationOptions" Margin="20" Background="White"> <Border BorderBrush="Gray" BorderThickness="1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10"> <Image Stretch="None" HorizontalAlignment="Left"> <Image.Source> <DrawingImage PresentationOptions:Freeze="True"> <DrawingImage.Drawing> <GeometryDrawing> <GeometryDrawing.Geometry> <!-- Create a composite shape. --> <GeometryGroup> <EllipseGeometry Center="50,50" RadiusX="45" RadiusY="20" /> <EllipseGeometry Center="50,50" RadiusX="20" RadiusY="45" /> </GeometryGroup> </GeometryDrawing.Geometry>
72
<GeometryDrawing.Brush> <!-- Paint the drawing with a gradient. --> <LinearGradientBrush> <GradientStop Offset="0.0" Color="Blue" /> <GradientStop Offset="1.0" Color="#CCCCFF" /> </LinearGradientBrush> </GeometryDrawing.Brush> <GeometryDrawing.Pen> <!-- Outline the drawing with a solid color. --> <Pen Thickness="10" Brush="Black" /> </GeometryDrawing.Pen> </GeometryDrawing> </DrawingImage.Drawing> </DrawingImage> </Image.Source> </Image> </Border> </Page>
The following illustration shows the resulting GeometryDrawing.
To create more complex drawings, you can combine multiple drawing objects into a single composite drawing using
a DrawingGroup.
See Also
Tasks
How to: Create a Composite Drawing
Reference
DrawingGroup
Concepts
Drawing Objects Overview
Geometry Overview
73
How to: Draw an Image Using ImageDrawing .NET Framework 4
This example shows how to use an ImageDrawing to draw an image. An ImageDrawing enables you display
an ImageSource with a DrawingBrush, DrawingImage, orVisual. To draw an image, you create an ImageDrawing and
set its ImageDrawing.ImageSource and ImageDrawing.Rect properties. The ImageDrawing.ImageSourceproperty
specifies the image to draw, and the ImageDrawing.Rect property specifies the position and size of each image.
Example
The following example creates a composite drawing using four ImageDrawing objects. This example produces the
following image:
Four ImageDrawing objects
C#
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Media.Imaging; namespace SDKSample { public class ImageDrawingExample : Page { public ImageDrawingExample() { // Create a DrawingGroup to combine the ImageDrawing objects. DrawingGroup imageDrawings = new DrawingGroup(); // Create a 100 by 100 image with an upper-left point of (75,75). ImageDrawing bigKiwi = new ImageDrawing(); bigKiwi.Rect = new Rect(75, 75, 100, 100); bigKiwi.ImageSource = new BitmapImage( new Uri(@"sampleImages\kiwi.png", UriKind.Relative)); imageDrawings.Children.Add(bigKiwi);
74
// Create a 25 by 25 image with an upper-left point of (0,150). ImageDrawing smallKiwi1 = new ImageDrawing(); smallKiwi1.Rect = new Rect(0, 150, 25, 25); smallKiwi1.ImageSource = new BitmapImage(new Uri(@"sampleImages\kiwi.png", UriKind.Relative)); imageDrawings.Children.Add(smallKiwi1); // Create a 25 by 25 image with an upper-left point of (150,0). ImageDrawing smallKiwi2 = new ImageDrawing(); smallKiwi2.Rect = new Rect(150, 0, 25, 25); smallKiwi2.ImageSource = new BitmapImage(new Uri(@"sampleImages\kiwi.png", UriKind.Relative)); imageDrawings.Children.Add(smallKiwi2); // Create a 75 by 75 image with an upper-left point of (0,0). ImageDrawing wholeKiwi = new ImageDrawing(); wholeKiwi.Rect = new Rect(0, 0, 75, 75); wholeKiwi.ImageSource = new BitmapImage(new Uri(@"sampleImages\wholekiwi.png", UriKind.Relative)); imageDrawings.Children.Add(wholeKiwi); // // Use a DrawingImage and an Image control to // display the drawings. // DrawingImage drawingImageSource = new DrawingImage(imageDrawings); // Freeze the DrawingImage for performance benefits. drawingImageSource.Freeze(); Image imageControl = new Image(); imageControl.Stretch = Stretch.None; imageControl.Source = drawingImageSource; // Create a border to contain the Image control. Border imageBorder = new Border(); imageBorder.BorderBrush = Brushes.Gray; imageBorder.BorderThickness = new Thickness(1); imageBorder.HorizontalAlignment = HorizontalAlignment.Left; imageBorder.VerticalAlignment = VerticalAlignment.Top; imageBorder.Margin = new Thickness(20); imageBorder.Child = imageControl; this.Background = Brushes.White; this.Margin = new Thickness(20); this.Content = imageBorder; } } }
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="PresentationOptions" Background="White" Margin="20"> <Border BorderBrush="Gray" BorderThickness="1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="20">
75
<Image Stretch="None"> <Image.Source> <DrawingImage PresentationOptions:Freeze="True"> <DrawingImage.Drawing> <DrawingGroup> <!-- The Rect property specifies that the image only fill a 100 by 100 rectangular area. --> <ImageDrawing Rect="75,75,100,100" ImageSource="sampleImages\kiwi.png"/> <!-- This image is set to fill a 25 by 25 rectangular area. --> <ImageDrawing Rect="0,150,25,25" ImageSource="sampleImages\kiwi.png"/> <!-- This image is set to fill a 25 by 25 rectangular area. --> <ImageDrawing Rect="150,0,25,25" ImageSource="sampleImages\kiwi.png"/> <!-- This image is set to fill a 75 by 75 rectangular area. --> <ImageDrawing Rect="0,0,75,75" ImageSource="sampleImages\wholekiwi.png"/> </DrawingGroup> </DrawingImage.Drawing> </DrawingImage> </Image.Source> </Image> </Border> </Page>
For an example showing a simple way to display an image without using ImageDrawing, see How to: Use the Image
Element.
See Also
Reference
Freeze
PresentationOptions:Freeze Attribute
Image
Concepts
Drawing Objects Overview
Freezable Objects Overview
76
How to: Play Media using a VideoDrawing .NET Framework 4
To play an audio or video file, you use a VideoDrawing and a MediaPlayer. There are two ways to load and play media.
The first is to use a MediaPlayer and aVideoDrawing by themselves, and the second way is to create your
own MediaTimeline to use with the MediaPlayer and VideoDrawing.
Note
When distributing media with your application, you cannot use a media file as a project resource, like you
would an image. In your project file, you must instead set the media type to Content and
set CopyToOutputDirectory to PreserveNewest or Always.
Example
The following example uses a VideoDrawing and a MediaPlayer to play a video file once.
C#
// // Create a VideoDrawing. // MediaPlayer player = new MediaPlayer(); player.Open(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative)); VideoDrawing aVideoDrawing = new VideoDrawing(); aVideoDrawing.Rect = new Rect(0, 0, 100, 100); aVideoDrawing.Player = player; // Play the video once. player.Play();
To gain additional timing control over the media, use a MediaTimeline with
the MediaPlayer and VideoDrawing objects. The MediaTimeline enables you to specify whether the video should
repeat.
The following example uses a MediaTimeline with the MediaPlayer and VideoDrawing objects to play a video
repeatedly.
C#
// // Create a VideoDrawing that repeats. // // Create a MediaTimeline. MediaTimeline mTimeline =
77
new MediaTimeline(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative)); // Set the timeline to repeat. mTimeline.RepeatBehavior = RepeatBehavior.Forever; // Create a clock from the MediaTimeline. MediaClock mClock = mTimeline.CreateClock(); MediaPlayer repeatingVideoDrawingPlayer = new MediaPlayer(); repeatingVideoDrawingPlayer.Clock = mClock; VideoDrawing repeatingVideoDrawing = new VideoDrawing(); repeatingVideoDrawing.Rect = new Rect(150, 0, 100, 100); repeatingVideoDrawing.Player = repeatingVideoDrawingPlayer;
Note that, when you use a MediaTimeline, you use the interactive ClockController returned from
the Controller property of the MediaClock to control media playback instead of the interactive methods
of MediaPlayer.
See Also
Reference
VideoDrawing
Concepts
Drawing Objects Overview
78
How to: Use a Drawing as an Image Source .NET Framework 4
This example shows how to use a Drawing as the Source for an Image control. To display a Drawing with
an Image control, use a DrawingImage as the Imagecontrol's Source and set
the DrawingImage object's DrawingImage.Drawing property to the drawing you want to display.
Example
The following example uses a DrawingImage and an Image control to display a GeometryDrawing. This example
produces the following output:
A DrawingImage
C#
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace SDKSample { public class DrawingImageExample : Page { public DrawingImageExample() { // // Create the Geometry to draw. // GeometryGroup ellipses = new GeometryGroup(); ellipses.Children.Add( new EllipseGeometry(new Point(50,50), 45, 20) ); ellipses.Children.Add( new EllipseGeometry(new Point(50, 50), 20, 45) ); // // Create a GeometryDrawing. // GeometryDrawing aGeometryDrawing = new GeometryDrawing(); aGeometryDrawing.Geometry = ellipses;
79
// Paint the drawing with a gradient. aGeometryDrawing.Brush = new LinearGradientBrush( Colors.Blue, Color.FromRgb(204,204,255), new Point(0,0), new Point(1,1)); // Outline the drawing with a solid color. aGeometryDrawing.Pen = new Pen(Brushes.Black, 10); // // Use a DrawingImage and an Image control to display the drawing. // DrawingImage geometryImage = new DrawingImage(aGeometryDrawing); // Freeze the DrawingImage for performance benefits. geometryImage.Freeze(); Image anImage = new Image(); anImage.Source = geometryImage; anImage.HorizontalAlignment = HorizontalAlignment.Left; // // Place the image inside a border and add it to the page. // Border exampleBorder = new Border(); exampleBorder.Child = anImage; exampleBorder.BorderBrush = Brushes.Gray; exampleBorder.BorderThickness = new Thickness(1); exampleBorder.HorizontalAlignment = HorizontalAlignment.Left; exampleBorder.VerticalAlignment = VerticalAlignment.Top; exampleBorder.Margin = new Thickness(10); this.Margin = new Thickness(20); this.Background = Brushes.White; this.Content = exampleBorder; } } }
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="PresentationOptions" Background="White" Margin="20"> <Border BorderBrush="Gray" BorderThickness="1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10"> <!-- This image uses a Drawing object for its source. --> <Image> <Image.Source> <DrawingImage PresentationOptions:Freeze="True"> <DrawingImage.Drawing> <GeometryDrawing> <GeometryDrawing.Geometry> <GeometryGroup>
80
<EllipseGeometry Center="50,50" RadiusX="45" RadiusY="20" /> <EllipseGeometry Center="50,50" RadiusX="20" RadiusY="45" /> </GeometryGroup> </GeometryDrawing.Geometry> <GeometryDrawing.Brush> <LinearGradientBrush> <GradientStop Offset="0.0" Color="Blue" /> <GradientStop Offset="1.0" Color="#CCCCFF" /> </LinearGradientBrush> </GeometryDrawing.Brush> <GeometryDrawing.Pen> <Pen Thickness="10" Brush="Black" /> </GeometryDrawing.Pen> </GeometryDrawing> </DrawingImage.Drawing> </DrawingImage> </Image.Source> </Image> </Border> </Page>
See Also
Tasks
How to: Draw an Image Using ImageDrawing
Reference
Freeze
PresentationOptions:Freeze Attribute
Concepts
Drawing Objects Overview
Freezable Objects Overview
81
Geometries .NET Framework 4
Geometry is a versatile class, used to render 2-D graphics, hit-test objects, and define clipping regions
In This Section
Path Markup Syntax
Geometry Overview
Geometries How-to Topics
See Also
Reference
Brushes
Shape
Concepts
Optimizing Performance: 2D Graphics and Imaging
Shapes and Basic Drawing in WPF Overview
Graphics and Multimedia
82
Path Markup Syntax .NET Framework 4
Paths are discussed in Shapes and Basic Drawing in WPF Overview and the Geometry Overview, however, this topic
describes in detail the powerful and complex mini-language you can use to specify path geometries more compactly
using Extensible Application Markup Language (XAML).
This topic contains the following sections.
Prerequisites
To understand this topic, you should be familiar with the basic features of Geometry objects. For more information,
see the Geometry Overview.
StreamGeometry and PathFigureCollection Mini-Languages
WPF provides two classes that provide mini-languages for describing geometric
paths: StreamGeometry and PathFigureCollection.
You use the StreamGeometry mini-language when setting a property of type Geometry, such as
the Clip property of a UIElement or the Data property of aPath element. The following example uses attribute
syntax to create a StreamGeometry.
XAML
<Path Stroke="Black" Fill="Gray" Data="M 10,100 C 10,300 300,-200 300,100" />
You use the PathFigureCollection mini-language when setting the Figures property of a PathGeometry. The
following example uses a attribute syntax to create a PathFigureCollection for a PathGeometry.
XAML
<Path Stroke="Black" Fill="Gray"> <Path.Data> <PathGeometry Figures="M 10,100 C 10,300 300,-200 300,100" /> </Path.Data> </Path>
As you can see from the preceding examples, the two mini-languages are very similar. It's always possible to use
a PathGeometry in any situation where you could use a StreamGeometry; so which one should you use? Use
a StreamGeometry when you don't need to modify the path after creating it; use aPathGeometry if you do need to
modify the path.
For more information about the differences between PathGeometry and StreamGeometry objects, see the Geometry
Overview.
A Note about White Space
For brevity, a single space is shown in the syntax sections that follow, but multiple spaces are also acceptable wherever
a single space is shown.
83
Two numbers don’t actually have to be separated by a comma or whitespace, but this can only be done when the
resulting string is unambiguous. For instance,2..3 is actually two numbers: "2." And ".3". Similarly, 2-3 is "2" and "-3".
Spaces are not required before or after commands, either.
Syntax
The Extensible Application Markup Language (XAML) attribute usage syntax for a StreamGeometry is composed of an
optional FillRule value and one or more figure descriptions.
StreamGeometry XAML Attribute Usage
< object property="[fillRule] figureDescription[figureDescription]*" ... />
The Extensible Application Markup Language (XAML) attribute usage syntax for a PathFigureCollection is composed of
one or more figure descriptions.
PathFigureCollection XAML Attribute Usage
< object property="figureDescription[figureDescription]*" ... />
Term Description
fillRule System.Windows.Media.FillRule
Specifies whether the StreamGeometry uses the EvenOdd or Nonzero FillRule. F0 specifies the EvenOdd fill rule.
F1 specifies the Nonzero fill rule.
If you omit this command, the subpath uses the default behavior, which is EvenOdd. If
you specify this command, you must place it first.
figureDescription A figure composed of a move command, draw commands, and an optional close
command.
moveCommand drawCommands [ closeCommand ]
moveCommand A move command that specifies the start point of the figure. See the Move
Command section.
drawCommands One or more drawing commands that describe the figure's contents. See the Draw
Commands section.
closeCommand An optional close command that closes figure. See the Close Command section.
Move Command
Specifies the start point of a new figure.
Syntax
M startPoint
- or -
m startPoint
84
Term Description
startPoint System.Windows.Point
The start point of a new figure.
An uppercase M indicates that startPoint is an absolute value; a lowercase m indicates that startPoint is an offset to
the previous point, or (0,0) if none exists. If you list multiple points after the move command, a line is drawn to those
points though you specified the line command.
Draw Commands
A draw command can consist of several shape commands. The following shape commands are available: line,
horizontal line, vertical line, cubic Bezier curve, quadratic Bezier curve, smooth cubic Bezier curve, smooth quadratic
Bezier curve, and elliptical arc.
You enter each command by using either an uppercase or a lowercase letter: uppercase letters denote absolute values
and lowercase letters denote relative values: the control points for that segment are relative to the end point of the
preceding example. When sequentially entering more than one command of the same type, you can omit the
duplicate command entry; for example, L 100,200 300,400 is equivalent to L 100,200 L 300,400. The
following table describes themove and draw commands.
Line Command
Creates a straight line between the current point and the specified end point. l 20 30 and L 20,30 are examples
of valid line commands.
Syntax
L endPoint
- or -
l endPoint
Term Description
endPoint System.Windows.Point
The end point of the line.
Horizontal Line Command
Creates a horizontal line between the current point and the specified x-coordinate. H 90 is an example of a valid
horizontal line command.
Syntax
H x
- or -
h x
85
Term Description
x System.Double
The x-coordinate of the end point of the line.
Vertical Line Command
Creates a vertical line between the current point and the specified y-coordinate. v 90 is an example of a valid vertical
line command.
Syntax
V y
- or -
v y
Term Description
y System.Double
The y-coordinate of the end point of the line.
Cubic Bezier Curve Command
Creates a cubic Bezier curve between the current point and the specified end point by using the two specified control
points (controlPoint1 and controlPoint2).C 100,200 200,400 300,200 is an example of a valid curve
command.
Syntax
C controlPoint1 controlPoint2 endPoint
- or - c controlPoint1 controlPoint2 endPoint
Term Description
controlPoint 1 System.Windows.Point
The first control point of the curve, which determines the starting tangent of the curve.
controlPoint 2 System.Windows.Point
The second control point of the curve, which determines the ending tangent of the curve.
endPoint System.Windows.Point
The point to which the curve is drawn.
Quadratic Bezier Curve Command
86
Creates a quadratic Bezier curve between the current point and the specified end point by using the specified control
point (controlPoint). q 100,200 300,200 is an example of a valid quadratic Bezier curve command.
Syntax
Q controlPoint endPoint
- or - q controlPoint endPoint
Term Description
controlPoint System.Windows.Point
The control point of the curve, which determines the starting and ending tangents of the
curve.
endPoint System.Windows.Point
The point to which the curve is drawn.
Smooth cubic Bezier curve Command
Creates a cubic Bezier curve between the current point and the specified end point. The first control point is assumed
to be the reflection of the second control point of the previous command relative to the current point. If there is no
previous command or if the previous command was not a cubic Bezier curve command or a smooth cubic Bezier curve
command, assume the first control point is coincident with the current point. The second control point, the control
point for the end of the curve, is specified by controlPoint2. For example, S 100,200 200,300 is a valid smooth
cubic Bezier curve command.
Syntax
S controlPoint2 endPoint
- or - s controlPoint2 endPoint
Term Description
controlPoint 2 System.Windows.Point
The control point of the curve, which determines the ending tangent of the curve.
endPoint System.Windows.Point
The point to which the curve is drawn.
Smooth quadratic Bezier curve Command
Creates a quadratic Bezier curve between the current point and the specified end point. The control point is assumed
to be the reflection of the control point of the previous command relative to the current point. If there is no previous
command or if the previous command was not a quadratic Bezier curve command or a smooth quadratic Bezier curve
command, the control point is coincident with the current point.
Syntax
87
T controlPoint endPoint
- or -
t controlPoint endPoint
Term Description
controlPoint System.Windows.Point
The control point of the curve, which determines the starting and tangent of the curve.
endPoint System.Windows.Point
The point to which the curve is drawn.
Elliptical Arc Command
Creates an elliptical arc between the current point and the specified end point.
Syntax
A size rotationAngle isLargeArcFlag sweepDirectionFlag endPoint
- or - a size rotationAngle isLargeArcFlag sweepDirectionFlag endPoint
Term Description
size System.Windows.Size
The x- and y-radius of the arc.
rotationAngle System.Double
The rotation of the ellipse, in degrees.
isLargeArcFlag Set to 1 if the angle of the arc should be 180 degrees or greater; otherwise, set to 0.
sweepDirectionFlag Set to 1 if the arc is drawn in a positive-angle direction; otherwise, set to 0.
endPoint System.Windows.Point
The point to which the arc is drawn.
The Close Command
Ends the current figure and creates a line that connects the current point to the starting point of the figure. This
command creates a line-join (corner) between the last segment and the first segment of the figure.
Syntax
Z
- or -
88
z
Point Syntax
Describes the x- and y-coordinates of a point.
Syntax
x , y
- or -
x y
Term Description
x System.Double
The x-coordinate of the point.
y System.Double
The y-coordinate of the point.
Special Values
Instead of a standard numerical value, you can also use the following special values. These values are case-sensitive.
Infinity
Represents Double.PositiveInfinity.
-Infinity
Represents Double.NegativeInfinity.
NaN
Represents Double.NaN.
You may also use scientific notation. For example, +1.e17 is a valid value.
See Also
Reference
Path
StreamGeometry
PathGeometry
PathFigureCollection
Concepts
Shapes and Basic Drawing in WPF Overview
Geometry Overview
Other Resources
Geometries How-to Topics
89
Geometry Overview .NET Framework 4
This overview describes how to use the Windows Presentation Foundation (WPF) Geometry classes to describe shapes.
This topic also contrasts the differences between Geometry objects and Shape elements.
This topic contains the following sections.
What Is a Geometry?
Geometries vs. Shapes
Common Properties That Take a Geometry
Simple Geometry Types
Path Geometries
Composite Geometries
Combined Geometries
Freezable Features
Other Geometry Features
Related Topics
What Is a Geometry?
The Geometry class and the classes which derive from it, such as EllipseGeometry, PathGeometry,
and CombinedGeometry, enable you to describe the geometry of a 2-D shape. These geometric descriptions have
many uses, such defining a shape to paint to the screen or defining hit-test and clip regions. You can even use a
geometry to define an animation path.
Geometry objects can be simple, such as rectangles and circles, or composite, created from two or more geometry
objects. More complex geometries can be created by using the PathGeometry and StreamGeometry classes, which
enable you to describe arcs and curves.
Because a Geometry is a type of Freezable, Geometry objects provide several special features: they can be declared
as resources, shared among multiple objects, made read-only to improve performance, cloned, and made thread-safe.
For more information about the different features provided by Freezableobjects, see the Freezable Objects Overview.
Geometries vs. Shapes
The Geometry and Shape classes seem similar in that they both describe 2-D shapes
(compare EllipseGeometry and Ellipse for example), but there are important differences.
For one, the Geometry class inherits from the Freezable class while the Shape class inherits from FrameworkElement.
Because they are elements, Shape objects can render themselves and participate in the layout system,
while Geometry objects cannot.
Although Shape objects are more readily usable than Geometry objects, Geometry objects are more versatile. While
a Shape object is used to render 2-D graphics, a Geometry object can be used to define the geometric region for 2-D
graphics, define a region for clipping, or define a region for hit testing, for example.
The Path Shape
One Shape, the Path class, actually uses a Geometry to describe its contents. By setting the Data property of
the Path with a Geometry and setting its Fill andStroke properties, you can render a Geometry.
90
Common Properties That Take a Geometry
The preceding sections mentioned that Geometry objects can be used with other objects for a variety of purposes,
such as drawing shapes, animating, and clipping. The following table lists several classes that have properties that take
a Geometry object.
Type Property
DoubleAnimationUsingPath PathGeometry
DrawingGroup ClipGeometry
GeometryDrawing Geometry
Path Data
UIElement Clip
Simple Geometry Types
The base class for all geometries is the abstract class Geometry. The classes which derive from the Geometry class can
be roughly grouped into three categories: simple geometries, path geometries, and composite geometries.
Simple geometry classes include LineGeometry, RectangleGeometry, and EllipseGeometry and are used to create basic
geometric shapes, such as lines, rectangles, and circles.
A LineGeometry is defined by specifying the start point of the line and the end point.
A RectangleGeometry is defined with a Rect structure which specifies its relative position and its height and
width. You can create a rounded rectangle by setting the RadiusX and RadiusYproperties.
An EllipseGeometry is defined by a center point, an x-radius and a y-radius. The following examples show how
to create simple geometries for rendering and for clipping.
These same shapes, as well as more complex shapes, can be created using a PathGeometry or by combining geometry
objects together, but these classes provide a simpler means for producing these basic geometric shapes.
The following example shows how to create and render a LineGeometry. As noted previously, a Geometry object is
unable to draw itself, so the example uses aPath shape to render the line. Because a line has no area, setting
the Fill property of the Path would have no effect; instead, only the Stroke and StrokeThicknessproperties are specified.
The following illustration shows the output from the example.
A LineGeometry drawn from (10,20) to (100,130)
XAML
<Path Stroke="Black" StrokeThickness="1" >
91
<Path.Data> <LineGeometry StartPoint="10,20" EndPoint="100,130" /> </Path.Data> </Path>
C#
VB
LineGeometry myLineGeometry = new LineGeometry(); myLineGeometry.StartPoint = new Point(10,20); myLineGeometry.EndPoint = new Point(100,130); Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; myPath.Data = myLineGeometry;
The next example shows how to create and render an EllipseGeometry. The examples sets the Center of
the EllipseGeometry is set to the point 50,50 and the x-radius and the y-radius are both set to 50, which creates a circle
with a diameter of 100. The interior of the ellipse is painted by assigning a value to the Path element's Fill property, in
this case Gold. The following illustration shows the output from the example.
An EllipseGeometry drawn at (50,50)
XAML
<Path Fill="Gold" Stroke="Black" StrokeThickness="1"> <Path.Data> <EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50" /> </Path.Data> </Path>
C#
VB
EllipseGeometry myEllipseGeometry = new EllipseGeometry(); myEllipseGeometry.Center = new Point(50, 50); myEllipseGeometry.RadiusX = 50; myEllipseGeometry.RadiusY = 50; Path myPath = new Path(); myPath.Fill = Brushes.Gold; myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; myPath.Data = myEllipseGeometry;
92
The following example shows how to create and render a RectangleGeometry. The position and the dimensions of the
rectangle are defined by a Rect structure. The position is 50,50 and the height and width are both 25, which creates a
square. The following illustration shows the output from the example.
A RectangleGeometry drawn at 50,50
XAML
<Path Fill="LemonChiffon" Stroke="Black" StrokeThickness="1"> <Path.Data> <RectangleGeometry Rect="50,50,25,25" /> </Path.Data> </Path>
C#
VB
RectangleGeometry myRectangleGeometry = new RectangleGeometry(); myRectangleGeometry.Rect = new Rect(50,50,25,25); Path myPath = new Path(); myPath.Fill = Brushes.LemonChiffon; myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; myPath.Data = myRectangleGeometry;
The following example shows how to use an EllipseGeometry as the clip region for an image. An Image object is
defined with a Width of 200 and a Height of 150. An EllipseGeometry with a RadiusX value of 100, a RadiusY value of
75, and a Center value of 100,75 is set to the Clip property of the image. Only the part of the image that is within the
area of the ellipse will be displayed. The following illustration shows the output from the example.
An EllipseGeometry used to clip an Image control
93
XAML
<Image Source="sampleImages\Waterlilies.jpg" Width="200" Height="150" HorizontalAlignment="Left"> <Image.Clip> <EllipseGeometry RadiusX="100" RadiusY="75" Center="100,75"/> </Image.Clip> </Image>
C#
VB
// Create the image to clip. Image myImage = new Image(); Uri imageUri = new Uri(@"C:\\Documents and Settings\\All Users\\Documents\My Pictures\\Sample Pictures\\Water lilies.jpg", UriKind.Relative); myImage.Source = new BitmapImage(imageUri); myImage.Width = 200; myImage.Height = 150; myImage.HorizontalAlignment = HorizontalAlignment.Left; // Use an EllipseGeometry to define the clip region. EllipseGeometry myEllipseGeometry = new EllipseGeometry(); myEllipseGeometry.Center = new Point(100, 75); myEllipseGeometry.RadiusX = 100; myEllipseGeometry.RadiusY = 75; myImage.Clip = myEllipseGeometry;
94
Path Geometries
The PathGeometry class and its light-weight equivalent, the StreamGeometry class, provide the means to describe
multiple complex figures composed of arcs, curves, and lines.
At the heart of a PathGeometry is a collection of PathFigure objects, so named because each figure describes a
discrete shape in the PathGeometry. EachPathFigure is itself comprised of one or more PathSegment objects, each of
which describes a segment of the figure.
There are many types of segments.
Segment Type Description Example
ArcSegment Creates an elliptical arc between
two points.
How to: Create an Elliptical Arc .
BezierSegment Creates a cubic Bezier curve
between two points.
How to: Create a Cubic Bezier Curve .
LineSegment Creates a line between two points. How to: Create a LineSegment in a
PathGeometry
PolyBezierSegment Creates a series of cubic Bezier
curves.
See the PolyBezierSegment type page.
PolyLineSegment Creates a series of lines. See the PolyLineSegment type page.
PolyQuadraticBezierSegment Creates a series of quadratic Bezier
curves.
See
the PolyQuadraticBezierSegment page.
QuadraticBezierSegment Creates a quadratic Bezier curve. How to: Create a Quadratic Bezier
Curve .
The segments within a PathFigure are combined into a single geometric shape with the end point of each segment
being the start point of the next segment. TheStartPoint property of a PathFigure specifies the point from which the
first segment is drawn. Each subsequent segment starts at the end point of the previous segment. For example, a
vertical line from 10,50 to 10,150 can be defined by setting the StartPoint property to 10,50 and creating
a LineSegment with a Pointproperty setting of 10,150.
The following example creates a simple PathGeometry comprised of a single PathFigure with a LineSegment and
displays it using a Path element. The PathFigureobject's StartPoint is set to 10,20 and a LineSegment is defined with an
end point of 100,130. The following illustration shows the PathGeometry created by this example.
A PathGeometry that contains a single LineSegment
95
XAML
<Path Stroke="Black" StrokeThickness="1"> <Path.Data> <PathGeometry> <PathGeometry.Figures> <PathFigure StartPoint="10,20"> <PathFigure.Segments> <LineSegment Point="100,130"/> </PathFigure.Segments> </PathFigure> </PathGeometry.Figures> </PathGeometry> </Path.Data> </Path>
C#
VB
// Create a figure that describes a // line from (10,20) to (100,130). PathFigure myPathFigure = new PathFigure(); myPathFigure.StartPoint = new Point(10,20); myPathFigure.Segments.Add( new LineSegment(new Point(100,130), true /* IsStroked */ )); /// Create a PathGeometry to contain the figure. PathGeometry myPathGeometry = new PathGeometry(); myPathGeometry.Figures.Add(myPathFigure); // Display the PathGeometry. Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; myPath.Data = myPathGeometry;
It is worth contrasting this example with the preceding LineGeometry example. The syntax used for a PathGeometry is
much more verbose than that used for a simple LineGeometry, and it may make more sense to use
the LineGeometry class in this case, but the verbose syntax of the PathGeometry allows for extremely intricate and
complex geometric regions.
More complex geometries can be created by using a combination of PathSegment objects.
The next example uses a BezierSegment, a LineSegment, and an ArcSegment to create shape. The example first creates
a cubic Bezier curve is by defining four points: a start point, which is the end point of the previous segment, an end
point (Point3), and two control points (Point1 and Point2). The two control points of a cubic Bezier curve behave like
magnets, attracting portions of what would otherwise be a straight line towards themselves, producing a curve. The
first control point, Point1, affects the beginning portion of the curve; the second control point, Point2, affects the
ending portion of the curve.
The example then adds a LineSegment, which is drawn between the end point of the preceding BezierSegment that
preceded it to the point specified by itsLineSegment property.
The example then adds an ArcSegment, which is drawn from the end point of the preceding LineSegment to the point
specified by its Point property. The example also specifies the arc's x- and y-radius (Size), a rotation angle
(RotationAngle), a flag indicating how large the angle of the resulting arc should be (IsLargeArc), and a value
96
indicating in which direction the arc is drawn (SweepDirection). The following illustration shows the shape created by
this example.
A PathGeometry
XAML <Path Stroke="Black" StrokeThickness="1" > <Path.Data> <PathGeometry> <PathGeometry.Figures> <PathFigure StartPoint="10,50"> <PathFigure.Segments> <BezierSegment Point1="100,0" Point2="200,200" Point3="300,100"/> <LineSegment Point="400,100" /> <ArcSegment Size="50,50" RotationAngle="45" IsLargeArc="True" SweepDirection="Clockwise" Point="200,100"/> </PathFigure.Segments> </PathFigure> </PathGeometry.Figures> </PathGeometry> </Path.Data> </Path>
C#
VB
// Create a figure. PathFigure myPathFigure = new PathFigure(); myPathFigure.StartPoint = new Point(10,50); myPathFigure.Segments.Add( new BezierSegment( new Point(100,0), new Point(200,200), new Point(300,100), true /* IsStroked */ )); myPathFigure.Segments.Add( new LineSegment( new Point(400,100), true /* IsStroked */ ));
97
myPathFigure.Segments.Add( new ArcSegment( new Point(200,100), new Size(50,50), 45, true, /* IsLargeArc */ SweepDirection.Clockwise, true /* IsStroked */ )); /// Create a PathGeometry to contain the figure. PathGeometry myPathGeometry = new PathGeometry(); myPathGeometry.Figures.Add(myPathFigure); // Display the PathGeometry. Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; myPath.Data = myPathGeometry;
Even more complex geometries can be created by using multiple PathFigure objects within a PathGeometry.
The following example creates a PathGeometry with two PathFigure objects, each of which contains
multiple PathSegment objects. The PathFigure from the above example and a PathFigure with a PolyLineSegment and
a QuadraticBezierSegment are used. A PolyLineSegment is defined with an array of points and
theQuadraticBezierSegment is defined with a control point and an end point. The following illustration shows the
shape created by this example.
A PathGeometry with multiple figures
XAML
<Path Stroke="Black" StrokeThickness="1" > <Path.Data> <PathGeometry> <PathGeometry.Figures> <PathFigure StartPoint="10,50"> <PathFigure.Segments> <BezierSegment Point1="100,0" Point2="200,200" Point3="300,100"/> <LineSegment Point="400,100" /> <ArcSegment Size="50,50" RotationAngle="45" IsLargeArc="True" SweepDirection="Clockwise"
98
Point="200,100"/> </PathFigure.Segments> </PathFigure> <PathFigure StartPoint="10,100"> <PathFigure.Segments> <PolyLineSegment Points="50,100 50,150" /> <QuadraticBezierSegment Point1="200,200" Point2="300,100"/> </PathFigure.Segments> </PathFigure> </PathGeometry.Figures> </PathGeometry> </Path.Data> </Path>
C#
VB
PathGeometry myPathGeometry = new PathGeometry(); // Create a figure. PathFigure pathFigure1 = new PathFigure(); pathFigure1.StartPoint = new Point(10,50); pathFigure1.Segments.Add( new BezierSegment( new Point(100,0), new Point(200,200), new Point(300,100), true /* IsStroked */ )); pathFigure1.Segments.Add( new LineSegment( new Point(400,100), true /* IsStroked */ )); pathFigure1.Segments.Add( new ArcSegment( new Point(200,100), new Size(50,50), 45, true, /* IsLargeArc */ SweepDirection.Clockwise, true /* IsStroked */ )); myPathGeometry.Figures.Add(pathFigure1); // Create another figure. PathFigure pathFigure2 = new PathFigure(); pathFigure2.StartPoint = new Point(10,100); Point[] polyLinePointArray = new Point[]{ new Point(50, 100), new Point(50, 150)}; PolyLineSegment myPolyLineSegment = new PolyLineSegment(); myPolyLineSegment.Points = new PointCollection(polyLinePointArray); pathFigure2.Segments.Add(myPolyLineSegment); pathFigure2.Segments.Add( new QuadraticBezierSegment( new Point(200,200), new Point(300,100), true /* IsStroked */ )); myPathGeometry.Figures.Add(pathFigure2); // Display the PathGeometry. Path myPath = new Path(); myPath.Stroke = Brushes.Black;
99
myPath.StrokeThickness = 1; myPath.Data = myPathGeometry;
StreamGeometry
Like the PathGeometry class, a StreamGeometry defines a complex geometric shape that may contain curves, arcs, and
lines. Unlike a PathGeometry, the contents of a StreamGeometry do not support data binding, animation, or
modification. Use a StreamGeometry when you need to describe a complex geometry but do not want the overhead
of supporting data binding, animation, or modification. Because of its efficiency, the StreamGeometry class is a good
choice for describing adorners.
For an example, see How to: Create a Shape Using a StreamGeometry.
Path Markup Syntax
The PathGeometry and StreamGeometry types support a Extensible Application Markup Language (XAML) attribute
syntax using a special series of move and draw commands. For more information, see Path Markup Syntax.
Composite Geometries
Composite geometry objects can be created using a GeometryGroup, a CombinedGeometry, or by calling the
static Geometry method Combine.
The CombinedGeometry object and the Combine method performs a Boolean operation to combine the area
defined by two geometries. Geometryobjects that have no area are discarded. Only two Geometry objects can
be combined (although these two geometries may also be composite geometries).
The GeometryGroup class creates an amalgamation of the Geometry objects it contains without combining
their area. Any number of Geometry objects can be added to a GeometryGroup. For an example, see How to:
Create a Composite Shape.
Because they do not perform a combine operation, using GeometryGroup objects provides performance benefits over
using CombinedGeometry objects or theCombine method.
Combined Geometries
The preceding section mentioned the CombinedGeometry object and the Combine method combine the area defined
by the geometries they contain. TheGeometryCombineMode enumeration specifies how the geometries are combined.
The possible values for the GeometryCombineMode property are: Union,Intersect, Exclude, and Xor.
In the following example, a CombinedGeometry is defined with a combine mode of Union. Both Geometry1 and
the Geometry2 are defined as circles of the same radius, but with centers offset by 50.
XAML
<Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF"> <Path.Data> <!-- Combines two geometries using the union combine mode. --> <CombinedGeometry GeometryCombineMode="Union"> <CombinedGeometry.Geometry1> <EllipseGeometry RadiusX="50" RadiusY="50" Center="75,75" /> </CombinedGeometry.Geometry1> <CombinedGeometry.Geometry2>
100
<EllipseGeometry RadiusX="50" RadiusY="50" Center="125,75" /> </CombinedGeometry.Geometry2> </CombinedGeometry> </Path.Data> </Path>
In the following example, a CombinedGeometry is defined with a combine mode of Xor. Both Geometry1 and
the Geometry2 are defined as circles of the same radius, but with centers offset by 50.
XAML
<Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF"> <Path.Data> <!-- Combines two geometries using the XOR combine mode. --> <CombinedGeometry GeometryCombineMode="Xor"> <CombinedGeometry.Geometry1> <EllipseGeometry RadiusX="50" RadiusY="50" Center="75,75" /> </CombinedGeometry.Geometry1> <CombinedGeometry.Geometry2> <EllipseGeometry RadiusX="50" RadiusY="50" Center="125,75" /> </CombinedGeometry.Geometry2> </CombinedGeometry> </Path.Data> </Path>
For additional examples, see How to: Create a Composite Shape and How to: Create a Combined Geometry.
Freezable Features
Because it inherits from the Freezable class, the Geometry class provide several special features: Geometry objects can
be declared as Resources Overview, shared among multiple objects, made read-only to improve performance, cloned,
and made thread-safe. For more information about the different features provided by Freezable objects, see
the Freezable Objects Overview.
101
Other Geometry Features
The Geometry class also provides useful utility methods, such as the following:
GetArea - Gets the area of the Geometry.
FillContains - Determines whether the Geometry contains another Geometry.
StrokeContains - Determines whether the stroke of a Geometry contains a specified point.
See the Geometry class for a complete listing of its methods.
See Also
Reference
Geometry
PathGeometry
Path
GeometryDrawing
Concepts
Optimizing Performance: 2D Graphics and Imaging
Path Markup Syntax
Animation Overview
Shapes and Basic Drawing in WPF Overview
Drawing Objects Overview
Other Resources
Geometries How-to Topics
102
Geometries How-to Topics .NET Framework 4
The topics in this section demonstrate how to use Geometry objects in your applications.
In This Section
How to: Animate an EllipseGeometry
How to: Animate the Size of an ArcSegment
How to: Control the Fill of a Composite Shape
How to: Create a Combined Geometry
How to: Create a Composite Shape
How to: Create a Cubic Bezier Curve
How to: Create a Line Using a LineGeometry
How to: Create a LineSegment in a PathGeometry
How to: Create a Shape by Using a PathGeometry
How to: Create a Shape Using a StreamGeometry
How to: Create a Quadratic Bezier Curve
How to: Create an Elliptical Arc
How to: Create Multiple Subpaths Within a PathGeometry
How to: Define a Rectangle Using a RectangleGeometry
How to: Round the Corners of a RectangleGeometry
See Also
Reference
Brushes
Shape
Concepts
Shapes and Basic Drawing in WPF Overview
Graphics and Multimedia
103
How to: Animate the Size of an ArcSegment .NET Framework 4
This example shows how to animate the Size property of an ArcSegment.
Example
The following example creates an ArcSegment that animates its Size when it loads on the screen.
C#
VB
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Shapes; using System.Windows.Media.Animation; using System.Windows.Media; namespace SDKSamples { public class SizeAnimationExample : Page { public SizeAnimationExample() { // Create a NameScope for this page so that // Storyboards can be used. NameScope.SetNameScope(this, new NameScope()); // Create an ArcSegment to define the geometry of the path. // The Size property of this segment is animated. ArcSegment myArcSegment = new ArcSegment(); myArcSegment.Size = new Size(90, 80); myArcSegment.SweepDirection = SweepDirection.Clockwise; myArcSegment.Point = new Point(500, 200); // Assign the segment a name so that // it can be targeted by a Storyboard. this.RegisterName( "myArcSegment", myArcSegment); PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection(); myPathSegmentCollection.Add(myArcSegment); // Create a PathFigure to be used for the PathGeometry of myPath. PathFigure myPathFigure = new PathFigure(); // Set the starting point for the PathFigure specifying that the // geometry starts at point 100,200. myPathFigure.StartPoint = new Point(100, 200); myPathFigure.Segments = myPathSegmentCollection; PathFigureCollection myPathFigureCollection = new PathFigureCollection(); myPathFigureCollection.Add(myPathFigure);
104
PathGeometry myPathGeometry = new PathGeometry(); myPathGeometry.Figures = myPathFigureCollection; // Create a path to draw a geometry with. Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; // specify the shape of the path using the path geometry. myPath.Data = myPathGeometry; SizeAnimation mySizeAnimation = new SizeAnimation(); mySizeAnimation.Duration = TimeSpan.FromSeconds(2); // Set the animation to repeat forever. mySizeAnimation.RepeatBehavior = RepeatBehavior.Forever; // Set the From and To properties of the animation. mySizeAnimation.From = new Size(90, 80); mySizeAnimation.To = new Size(200, 200); // Set the animation to target the Size property // of the object named "myArcSegment." Storyboard.SetTargetName(mySizeAnimation, "myArcSegment"); Storyboard.SetTargetProperty( mySizeAnimation, new PropertyPath(ArcSegment.SizeProperty)); // Create a storyboard to apply the animation. Storyboard ellipseStoryboard = new Storyboard(); ellipseStoryboard.Children.Add(mySizeAnimation); // Start the storyboard when the Path loads. myPath.Loaded += delegate(object sender, RoutedEventArgs e) { ellipseStoryboard.Begin(this); }; Canvas containerCanvas = new Canvas(); containerCanvas.Children.Add(myPath); Content = containerCanvas; } } }
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Canvas HorizontalAlignment="Left" Margin="0" > <!-- Create an arc on the screen that animates its size when it loads. --> <Path Stroke="Black" StrokeThickness="2" > <Path.Data> <PathGeometry> <PathGeometry.Figures> <PathFigureCollection> <PathFigure StartPoint="100,200"> <PathFigure.Segments> <PathSegmentCollection> <ArcSegment x:Name="myArcSegment" Size="90,80" SweepDirection="Clockwise" Point="500,200" /> </PathSegmentCollection> </PathFigure.Segments>
105
</PathFigure> </PathFigureCollection> </PathGeometry.Figures> </PathGeometry> </Path.Data> <Path.Triggers> <EventTrigger RoutedEvent="Path.Loaded"> <BeginStoryboard Name="myBeginStoryBoard"> <Storyboard> <!-- Animate the size of the ArcSegment to a width and height of 200. --> <SizeAnimation Storyboard.TargetName="myArcSegment" Storyboard.TargetProperty="Size" From="90,80" To="200,200" Duration="0:0:2" /> </Storyboard> </BeginStoryboard> </EventTrigger> </Path.Triggers> </Path> </Canvas> </Page>
For additional geometry and animation samples, see the Geometries Sample.
See Also
Reference
Size
ArcSegment
Concepts
Animation Overview
Geometry Overview
Other Resources
Geometries How-to Topics
Animation and Timing
Animation and Timing How-to Topics
106
How to: Control the Fill of a Composite Shape .NET Framework 4
The FillRule property of a GeometryGroup or a PathGeometry, specifies a "rule" which the composite shape uses to
determine whether a given point is part of the geometry. There are two possible values
for FillRule: EvenOdd and Nonzero. The following sections will describe how to use these two rules.
EvenOdd: This rule determines whether a point is in the fill region by drawing a ray from that point to infinity in any
direction and counting the number of path segments within the given shape that the ray crosses. If this number is odd,
the point is inside; if even, the point is outside.
For example, the XAML below creates a composite shape made up of a series of concentric rings (target) with
a FillRule set to EvenOdd.
XAML
<Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF"> <Path.Data> <GeometryGroup FillRule="EvenOdd"> <EllipseGeometry RadiusX="50" RadiusY="50" Center="75,75" /> <EllipseGeometry RadiusX="70" RadiusY="70" Center="75,75" /> <EllipseGeometry RadiusX="100" RadiusY="100" Center="75,75" /> <EllipseGeometry RadiusX="120" RadiusY="120" Center="75,75" /> </GeometryGroup> </Path.Data> </Path>
The following illustration shows the shape created in the previous example.
In the illustration above, notice that the center and 3rd ring are not filled. This is because a ray drawn from any point
within either of those two rings passes through an even number of segments. See illustration below:
NonZero: This rule determines whether a point is in the fill region of the path by drawing a ray from that point to
infinity in any direction and then examining the places where a segment of the shape crosses the ray. Starting with a
107
count of zero, add one each time a Segment crosses the ray from left to right and subtract one each time a path
segment crosses the ray from right to left. After counting the crossings, if the result is zero then the point is outside
the path. Otherwise, it is inside.
XAML
<Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF"> <Path.Data> <GeometryGroup FillRule="NonZero"> <EllipseGeometry RadiusX="50" RadiusY="50" Center="75,75" /> <EllipseGeometry RadiusX="70" RadiusY="70" Center="75,75" /> <EllipseGeometry RadiusX="100" RadiusY="100" Center="75,75" /> <EllipseGeometry RadiusX="120" RadiusY="120" Center="75,75" /> </GeometryGroup> </Path.Data> </Path>
Using the example above, a value of Nonzero for FillRule gives the following illustration as a result:
As you can see, all the rings are filled. This is because all the segments are running in the same direction and so a ray
drawn from any point will cross one or more segments and the sum of the crossings will not equal zero. For example,
in the illustration below, the red arrows represent the direction the segments are drawn and the white arrow
represents an arbitrary ray running from a point in the innermost ring. Starting with a value of zero, for each segment
that the ray crosses, a value of one is added because the segment crosses the ray from left to right.
To better demonstrate the behavior of Nonzero rule a more complex shape with segments running in different
directions is required. The XAML code below creates a similar shape as the previous example except that it is created
with a PathGeometry rather then a EllipseGeometry which creates four concentric arcs rather then fully closed
concentric circles.
XAML
<Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF"> <Path.Data> <GeometryGroup FillRule="NonZero"> <PathGeometry>
108
<PathGeometry.Figures> <!-- Inner Ring --> <PathFigure StartPoint="10,120"> <PathFigure.Segments> <PathSegmentCollection> <ArcSegment Size="50,50" IsLargeArc="True" SweepDirection="CounterClockwise" Point="25,120" /> </PathSegmentCollection> </PathFigure.Segments> </PathFigure> <!-- Second Ring --> <PathFigure StartPoint="10,100"> <PathFigure.Segments> <PathSegmentCollection> <ArcSegment Size="70,70" IsLargeArc="True" SweepDirection="CounterClockwise" Point="25,100" /> </PathSegmentCollection> </PathFigure.Segments> </PathFigure> <!-- Third Ring (Not part of path) --> <PathFigure StartPoint="10,70"> <PathFigure.Segments> <PathSegmentCollection> <ArcSegment Size="100,100" IsLargeArc="True" SweepDirection="CounterClockwise" Point="25,70" /> </PathSegmentCollection> </PathFigure.Segments> </PathFigure> <!-- Outer Ring --> <PathFigure StartPoint="10,300"> <PathFigure.Segments> <ArcSegment Size="130,130" IsLargeArc="True" SweepDirection="Clockwise" Point="25,300" /> </PathFigure.Segments> </PathFigure> </PathGeometry.Figures> </PathGeometry> </GeometryGroup> </Path.Data> </Path>
The following illustration shows the shape created in the previous example.
Notice that the third arc from the center is not filled. The illustration below shows why this is. In the illustration, the red
arrows represent the direction the segments are drawn. The two white arrows represent two arbitrary rays that move
out from a point in the "non-filled" region. As can be seen from the illustration, the sum of the values from a given ray
crossing the segments in its path is zero. As defined above, a sum of zero means that the point is not part of the
geometry (not part of the fill) while a sum that is not zero, including a negative value, is part of the geometry.
109
Note: For the purposes of FillRule, all shapes are considered closed. If there is a gap in a segment, draw an imaginary
line to close it. In the example above, there are small gaps in the rings. Given this, one might expect a ray that runs
through the gap to give a different result then a ray running in another direction. Below is an enlarged illustration of
one of these gaps and the "imaginary segment" (segment that is drawn for purposes of applying the FillRule) that
closes it.
See Also
Tasks
How to: Create a Composite Shape
Concepts
Geometry Overview
110
How to: Create a Combined Geometry .NET Framework 4
This example shows how to combine geometries. To combine two geometries, use a CombinedGeometry object. Set
its Geometry1 and Geometry2 properties with the two geometries to combine, and set
the GeometryCombineMode property, which determines how the geometries will be combined together,
to Union,Intersect, Exclude, or Xor.
To create a composite geometry from two or more geometries, use a GeometryGroup.
Example
In the following example, a CombinedGeometry is defined with a geometry combine mode of Exclude.
Both Geometry1 and the Geometry2 are defined as circles of the same radius, but with centers offset by 50.
XAML
<Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF"> <Path.Data> <!-- Combines two geometries using the exclude combine mode. --> <CombinedGeometry GeometryCombineMode="Exclude"> <CombinedGeometry.Geometry1> <EllipseGeometry RadiusX="50" RadiusY="50" Center="75,75" /> </CombinedGeometry.Geometry1> <CombinedGeometry.Geometry2> <EllipseGeometry RadiusX="50" RadiusY="50" Center="125,75" /> </CombinedGeometry.Geometry2> </CombinedGeometry> </Path.Data> </Path>
Combined Geometry Exclude
In the following markup, a CombinedGeometry is defined with a combine mode of Intersect. Both Geometry1 and
the Geometry2 are defined as circles of the same radius, but with centers offset by 50.
XAML
<Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF"> <Path.Data>
111
<!-- Combines two geometries using the intersect combine mode. --> <CombinedGeometry GeometryCombineMode="Intersect"> <CombinedGeometry.Geometry1> <EllipseGeometry RadiusX="50" RadiusY="50" Center="75,75" /> </CombinedGeometry.Geometry1> <CombinedGeometry.Geometry2> <EllipseGeometry RadiusX="50" RadiusY="50" Center="125,75" /> </CombinedGeometry.Geometry2> </CombinedGeometry> </Path.Data> </Path>
Combined Geometry Intersect
In the following markup, a CombinedGeometry is defined with a combine mode of Union. Both Geometry1 and
the Geometry2 are defined as circles of the same radius, but with centers offset by 50.
XAML
<Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF"> <Path.Data> <!-- Combines two geometries using the union combine mode. --> <CombinedGeometry GeometryCombineMode="Union"> <CombinedGeometry.Geometry1> <EllipseGeometry RadiusX="50" RadiusY="50" Center="75,75" /> </CombinedGeometry.Geometry1> <CombinedGeometry.Geometry2> <EllipseGeometry RadiusX="50" RadiusY="50" Center="125,75" /> </CombinedGeometry.Geometry2> </CombinedGeometry> </Path.Data> </Path>
Combined Geometry Union
112
In the following markup, a CombinedGeometry is defined with a combine mode of Xor. Both Geometry1 and
the Geometry2 are defined as circles of the same radius, but with centers offset by 50.
XAML
<Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF"> <Path.Data> <!-- Combines two geometries using the XOR combine mode. --> <CombinedGeometry GeometryCombineMode="Xor"> <CombinedGeometry.Geometry1> <EllipseGeometry RadiusX="50" RadiusY="50" Center="75,75" /> </CombinedGeometry.Geometry1> <CombinedGeometry.Geometry2> <EllipseGeometry RadiusX="50" RadiusY="50" Center="125,75" /> </CombinedGeometry.Geometry2> </CombinedGeometry> </Path.Data> </Path>
Combined Geometry Xor
113
How to: Create a Composite Shape .NET Framework 4
This example shows how to create composite shapes using Geometry objects and display them using a Path element.
In the following example, a LineGeometry,EllipseGeometry, and a RectangleGeometry are used with
a GeometryGroup to create a composite shape. The geometries are then drawn using a Path element.
Example
XAML
<!-- Displays the geometry. --> <Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF"> <Path.Data> <!-- Creates a composite shape from three geometries. --> <GeometryGroup FillRule="EvenOdd"> <LineGeometry StartPoint="10,10" EndPoint="50,30" /> <EllipseGeometry Center="40,70" RadiusX="30" RadiusY="30" /> <RectangleGeometry Rect="30,55 100 30" /> </GeometryGroup> </Path.Data> </Path>
C#
VB
// Create a Path to be drawn to the screen. Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; SolidColorBrush mySolidColorBrush = new SolidColorBrush(); mySolidColorBrush.Color = Color.FromArgb(255, 204, 204, 255); myPath.Fill = mySolidColorBrush; // Create the line geometry to add to the Path LineGeometry myLineGeometry = new LineGeometry(); myLineGeometry.StartPoint = new Point(10, 10); myLineGeometry.EndPoint = new Point(50, 30); // Create the ellipse geometry to add to the Path EllipseGeometry myEllipseGeometry = new EllipseGeometry(); myEllipseGeometry.Center = new Point(40, 70); myEllipseGeometry.RadiusX = 30; myEllipseGeometry.RadiusY = 30; // Create a rectangle geometry to add to the Path RectangleGeometry myRectGeometry = new RectangleGeometry(); myRectGeometry.Rect = new Rect(30, 55, 100, 30); // Add all the geometries to a GeometryGroup. GeometryGroup myGeometryGroup = new GeometryGroup(); myGeometryGroup.Children.Add(myLineGeometry); myGeometryGroup.Children.Add(myEllipseGeometry); myGeometryGroup.Children.Add(myRectGeometry);
114
myPath.Data = myGeometryGroup; // Add path shape to the UI. StackPanel mainPanel = new StackPanel(); mainPanel.Children.Add(myPath); this.Content = mainPanel;
The following illustration shows the shape created in the previous example.
Composite Geometry
More complex shapes, such as polygons and shapes with curved segments, may be created using a PathGeometry. For
an example showing how to create a shape using a PathGeometry, see How to: Create a Shape by Using a
PathGeometry. Although this example renders a shape to the screen using a Path element,Geometry objects may also
be used to describe the contents of a GeometryDrawing or a DrawingContext. They may also be used for clipping and
hit-testing.
This example is part of larger sample; for the complete sample, see the Geometries Sample.
115
How to: Create a Line Using a LineGeometry .NET Framework 4
This example shows how to use the LineGeometry class to describe a line. A LineGeometry is defined by its start and
end points.
Example
The following example shows how to create and render a LineGeometry. A Path element is used to render the line.
Since a line has no area, the Path object's Fillis not specified; instead the Stroke and StrokeThickness properties are
used.
XAML
<Path Stroke="Black" StrokeThickness="1" > <Path.Data> <LineGeometry StartPoint="10,20" EndPoint="100,130" /> </Path.Data> </Path>
C#
VB
LineGeometry myLineGeometry = new LineGeometry(); myLineGeometry.StartPoint = new Point(10,20); myLineGeometry.EndPoint = new Point(100,130); Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; myPath.Data = myLineGeometry;
A LineGeometry drawn from (10,20) to (100,130)
Other simple geometry classes include LineGeometry and EllipseGeometry. These geometries, as well as more complex
ones, can also be created using aPathGeometry or StreamGeometry. For more information, see the Geometry
Overview.
See Also
116
Tasks
How to: Create a Composite Shape
How to: Create a Shape by Using a PathGeometry
Concepts
Geometry Overview
117
How to: Create a LineSegment in a PathGeometry .NET Framework 4
This example shows how to create a line segment. To create a line segment, use the PathGeometry, PathFigure,
and LineSegment classes.
Example
The following examples draw a LineSegment from (10, 50) to (200, 70). The following illustration shows the
resulting LineSegment; a grid background was added to show the coordinate system.
A LineSegment drawn from (10,50) to (200,700)
[xaml]
In Extensible Application Markup Language (XAML), you may use attribute syntax to describe a path.
XAML
<Path Stroke="Black" StrokeThickness="1" Data="M 10,50 L 200,70" />
[xaml]
(Note that this attribute syntax actually creates a StreamGeometry, a lighter-weight version of a PathGeometry. For
more information, see the Path Markup Syntaxpage.)
In XAML, you may also draw a line segment by using object element syntax. The following is equivalent to the previous
XAML example.
C#
VB
PathFigure myPathFigure = new PathFigure(); myPathFigure.StartPoint = new Point(10, 50); LineSegment myLineSegment = new LineSegment(); myLineSegment.Point = new Point(200, 70); PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
118
myPathSegmentCollection.Add(myLineSegment); myPathFigure.Segments = myPathSegmentCollection; PathFigureCollection myPathFigureCollection = new PathFigureCollection(); myPathFigureCollection.Add(myPathFigure); PathGeometry myPathGeometry = new PathGeometry(); myPathGeometry.Figures = myPathFigureCollection; Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; myPath.Data = myPathGeometry;
XAML
<Path Stroke="Black" StrokeThickness="1"> <Path.Data> <PathGeometry> <PathFigure StartPoint="10,50"> <LineSegment Point="200,70" /> </PathFigure> </PathGeometry> </Path.Data> </Path>
This example is part of larger sample; for the complete sample, see the Geometries Sample.
See Also
Reference
PathFigure
PathGeometry
GeometryDrawing
Path
Concepts
Geometry Overview
119
How to: Create a Shape by Using a PathGeometry .NET Framework 4
This example shows how to create a shape using the PathGeometry class. PathGeometry objects are composed of one
or more PathFigure objects; each PathFigurerepresents a different "figure" or shape. Each PathFigure is itself
composed of one or more PathSegment objects, each representing a connected portion of the figure or shape.
Segment types include LineSegment, ArcSegment, and BezierSegment.
Example
The following example uses a PathGeometry to create a triangle. The PathGeometry is displayed using a Path element.
XAML
<Path Stroke="Black" StrokeThickness="1"> <Path.Data> <PathGeometry> <PathGeometry.Figures> <PathFigureCollection> <PathFigure IsClosed="True" StartPoint="10,100"> <PathFigure.Segments> <PathSegmentCollection> <LineSegment Point="100,100" /> <LineSegment Point="100,50" /> </PathSegmentCollection> </PathFigure.Segments> </PathFigure> </PathFigureCollection> </PathGeometry.Figures> </PathGeometry> </Path.Data> </Path>
The following illustration shows the shape created in the previous example.
A triangle created with a PathGeometry
120
The previous example showed how to create a relatively simple shape, a triangle. A PathGeometry can also be used to
create more complex shapes, including arcs and curves. For examples, see How to: Create an Elliptical Arc, How to:
Create a Cubic Bezier Curve, and How to: Create a Quadratic Bezier Curve.
This example is part of larger sample; for the complete sample, see the Geometries Sample.
See Also
Reference
Path
GeometryDrawing
Concepts
Geometry Overview
Other Resources
Geometries Sample
121
How to: Create a Shape Using a StreamGeometry .NET Framework 4
StreamGeometry is light-weight alternative to PathGeometry for creating geometric shapes. Use
a StreamGeometry when you need to describe a complex geometry but do not want the overhead of supporting data
binding, animation, or modification. For example, because of its efficiency, the StreamGeometry class is a good choice
for describing adorners.
Example
The following example uses attribute syntax to create a triangular StreamGeometry in XAML.
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel> <Path Data="F0 M10,100 L100,100 100,50Z" StrokeThickness="1" Stroke="Black"/> </StackPanel> </Page>
For more information about StreamGeometry attribute syntax, see the Path Markup Syntax page.
The next example uses a StreamGeometry to define a triangle in code. First, the example creates a StreamGeometry,
then obtains a StreamGeometryContext and uses it to describe the triangle.
C#
VB
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; namespace SDKSample { // Use StreamGeometry with StreamGeometryContext to define a triangle shape. public partial class StreamGeometryTriangleExample : Page { public StreamGeometryTriangleExample() { // Create a path to draw a geometry with. Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; // Create a StreamGeometry to use to specify myPath. StreamGeometry geometry = new StreamGeometry();
122
geometry.FillRule = FillRule.EvenOdd; // Open a StreamGeometryContext that can be used to describe this StreamGeometry // object's contents. using (StreamGeometryContext ctx = geometry.Open()) { // Begin the triangle at the point specified. Notice that the shape is set to // be closed so only two lines need to be specified below to make the triangle. ctx.BeginFigure(new Point(10, 100), true /* is filled */, true /* is closed */); // Draw a line to the next specified point. ctx.LineTo(new Point(100, 100), true /* is stroked */, false /* is smooth join */); // Draw another line to the next specified point. ctx.LineTo(new Point(100, 50), true /* is stroked */, false /* is smooth join */); } // Freeze the geometry (make it unmodifiable) // for additional performance benefits. geometry.Freeze(); // Specify the shape (triangle) of the Path using the StreamGeometry. myPath.Data = geometry; // Add path shape to the UI. StackPanel mainPanel = new StackPanel(); mainPanel.Children.Add(myPath); this.Content = mainPanel; } } }
The next example creates a method that uses a StreamGeometry and StreamGeometryContext to define a geometric
shape based on specified parameters.
C#
VB
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; namespace SDKSample { public partial class StreamGeometryExample : Page { public StreamGeometryExample() { // Create a path to draw a geometry with. Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; // Create a StreamGeometry to use to specify myPath. StreamGeometry theGeometry = BuildRegularPolygon(new Point(200, 200), 200, 8, 0);
123
theGeometry.FillRule = FillRule.EvenOdd; // Freeze the geometry (make it unmodifiable) // for additional performance benefits. theGeometry.Freeze(); // Use the StreamGeometry returned by the BuildRegularPolygon to // specify the shape of the path. myPath.Data = theGeometry; // Add path shape to the UI. StackPanel mainPanel = new StackPanel(); mainPanel.Children.Add(myPath); this.Content = mainPanel; } StreamGeometry BuildRegularPolygon(Point c, double r, int numSides, double offsetDegree) { // c is the center, r is the radius, // numSides the number of sides, offsetDegree the offset in Degrees. // Do not add the last point. StreamGeometry geometry = new StreamGeometry(); using (StreamGeometryContext ctx = geometry.Open()) { ctx.BeginFigure(new Point(), true /* is filled */, true /* is closed */); double step = 2 * Math.PI / Math.Max(numSides, 3); Point cur = c; double a = Math.PI * offsetDegree / 180.0; for (int i = 0; i < numSides; i++, a += step) { cur.X = c.X + r * Math.Cos(a); cur.Y = c.Y + r * Math.Sin(a); ctx.LineTo(cur, true /* is stroked */, false /* is smooth join */); } } return geometry; } } }
See Also
Tasks
How to: Create a Shape by Using a PathGeometry
Reference
PathGeometry
StreamGeometry
StreamGeometryContext
Concepts
Geometry Overview
124
How to: Create an Elliptical Arc .NET Framework 4
This example shows how to draw an elliptical arc. To create an elliptical arc, use the PathGeometry, PathFigure,
and ArcSegment classes.
Example
In the following examples, an elliptical arc is drawn from (10,100) to (200,100). The arc has a Size of 100 by 50 device-
independent pixels, a RotationAngle of 45 degrees, an IsLargeArc setting of true, and
a SweepDirection of Counterclockwise.
[xaml]
In Extensible Application Markup Language (XAML), you can use attribute syntax to describe a path.
XAML
<Path Stroke="Black" StrokeThickness="1" Data="M 10,100 A 100,50 45 1 0 200,100" />
[xaml]
(Note that this attribute syntax actually creates a StreamGeometry, a lighter-weight version of a PathGeometry. For
more information, see the Path Markup Syntaxpage.)
In XAML, you can also draw an elliptical arc by explicitly using object tags. The following is equivalent to the preceding
XAML markup.
XAML
<Path Stroke="Black" StrokeThickness="1"> <Path.Data> <PathGeometry> <PathGeometry.Figures> <PathFigureCollection> <PathFigure StartPoint="10,100"> <PathFigure.Segments> <PathSegmentCollection> <ArcSegment Size="100,50" RotationAngle="45" IsLargeArc="True" SweepDirection="CounterClockwise" Point="200,100" /> </PathSegmentCollection> </PathFigure.Segments> </PathFigure> </PathFigureCollection> </PathGeometry.Figures> </PathGeometry> </Path.Data> </Path>
125
This example is part of a larger sample. For the complete sample, see the Geometries Sample.
See Also
Tasks
How to: Create a Quadratic Bezier Curve
How to: Create a Cubic Bezier Curve
126
How to: Create Multiple Subpaths Within a
PathGeometry .NET Framework 4
This example shows how to create multiple subpaths in a PathGeometry. To create multiple subpaths, you create
a PathFigure for each subpath.
Example
The following example creates two subpaths, each one a triangle.
XAML
<Path Stroke="Black" StrokeThickness="1"> <Path.Data> <PathGeometry> <PathGeometry.Figures> <PathFigureCollection> <PathFigure IsClosed="True" StartPoint="10,100"> <PathFigure.Segments> <PathSegmentCollection> <LineSegment Point="100,100" /> <LineSegment Point="100,50" /> </PathSegmentCollection> </PathFigure.Segments> </PathFigure> <PathFigure IsClosed="True" StartPoint="10,10"> <PathFigure.Segments> <PathSegmentCollection> <LineSegment Point="100,10" /> <LineSegment Point="100,40" /> </PathSegmentCollection> </PathFigure.Segments> </PathFigure> </PathFigureCollection> </PathGeometry.Figures> </PathGeometry> </Path.Data> </Path>
The following example shows how to create multiple subpaths by using a Path and XAML attribute syntax.
Each M creates a new subpath so that the example creates two subpaths that each draw a triangle.
XAML
<Path Stroke="Black" StrokeThickness="1" Data="M 10,100 L 100,100 100,50 Z M 10,10 100,10 100,40 Z" />
(Note that this attribute syntax actually creates a StreamGeometry, a lighter-weight version of a PathGeometry. For
more information, see the Path Markup Syntaxpage.)
127
How to: Round the Corners of a RectangleGeometry .NET Framework 4
To round the corners of a RectangleGeometry, set its RadiusX and RadiusY properties to a value greater than zero. The
larger the values, the rounder the rectangle's corners.
Example
The following example shows several RectangleGeometry objects with different RadiusX and RadiusY settings.
The RectangleGeometry objects are displayed using Path elements.
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="GeoOvwSample.RectangleGeometryRoundedCornerExample"> <Page.Resources> <!-- Create a grid background to highlight the coordinate system. --> <DrawingBrush x:Key="GridDrawingBrushResource" Viewport="0,0,10,10" ViewportUnits="Absolute" TileMode="Tile"> <DrawingBrush.Drawing> <DrawingGroup> <DrawingGroup.Children> <GeometryDrawing Brush="White"> <GeometryDrawing.Geometry> <RectangleGeometry Rect="0,0,1,1" /> </GeometryDrawing.Geometry> </GeometryDrawing> <GeometryDrawing Geometry="M0,0 L1,0 1,0.1, 0,0.1Z" Brush="#CCCCFF" /> <GeometryDrawing Geometry="M0,0 L0,1 0.1,1, 0.1,0Z" Brush="#CCCCFF" /> </DrawingGroup.Children> </DrawingGroup> </DrawingBrush.Drawing> </DrawingBrush> <!-- Create a graph paper style border to frame the rectangles. --> <Style x:Key="GraphPaperBorderStyle" TargetType="{x:Type Border}"> <Setter Property="HorizontalAlignment" Value="Left" /> <Setter Property="Background" Value="{StaticResource GridDrawingBrushResource}" /> <Setter Property="BorderBrush" Value="Black" /> <Setter Property="BorderThickness" Value="1" /> <Setter Property="Margin" Value="10" /> <Setter Property="Width" Value="190" /> <Setter Property="Height" Value="90" /> </Style> </Page.Resources> <StackPanel Name="MainStackPanel"> <Border Style="{StaticResource GraphPaperBorderStyle}"> <Path Stroke="Black" StrokeThickness="1" Fill="#99CCCCFF"> <Path.Data>
128
<!-- Create a rectangle without rounded corners. --> <RectangleGeometry Rect="20,20,150,50" /> </Path.Data> </Path> </Border> <Border Style="{StaticResource GraphPaperBorderStyle}"> <Path Stroke="Black" StrokeThickness="1" Fill="#99CCCCFF"> <Path.Data> <!-- Create a rectangle with rounded corners by giving the RectangleGeometry a RadiusX and a RadiusY of 10. --> <RectangleGeometry Rect="20,20,150,50" RadiusX="10" RadiusY="10" /> </Path.Data> </Path> </Border> <Border Style="{StaticResource GraphPaperBorderStyle}" > <Path Stroke="Black" StrokeThickness="1" Fill="#99CCCCFF"> <Path.Data> <!-- Set RadiusX and RadiusY to their maximum values (half the rectangle's width and half the rectangle's height). --> <RectangleGeometry Rect="20,20,150,50" RadiusX="75" RadiusY="25" /> </Path.Data> </Path> </Border> </StackPanel> </Page>
Rectangles with Rounded Corners
See Also
Tasks
How to: Create a Composite Shape
How to: Create a Shape by Using a PathGeometry
Concepts
Geometry Overview
129
Painting with Images, Drawings, and Visuals .NET Framework 4
This topic describes how to use ImageBrush, DrawingBrush, and VisualBrush objects to paint an area with an image,
a Drawing, or a Visual.
This topic contains the following sections.
Prerequisites
Paint an Area with an Image
Example: Paint an Object with a Bitmap Image
Paint an Area with a Drawing
Example: Paint an Object with a Drawing
Paint an Area with a Visual
Example: Paint an Object with a Visual
Example: Create a Reflection
TileBrush Features
Related Topics
Prerequisites
To understand this topic, you should be familiar with the different types of brushes Windows Presentation Foundation
(WPF) provides and their basic features. For an introduction, see the WPF Brushes Overview.
Paint an Area with an Image
An ImageBrush paints an area with an ImageSource. The most common type of ImageSource to use with
an ImageBrush is a BitmapImage, which describes a bitmap graphic. You can use a DrawingImage to paint using
a Drawing object, but it is simpler to use a DrawingBrush instead. For more information aboutImageSource objects,
see the Imaging Overview.
To paint with an ImageBrush, create a BitmapImage and use it to load the bitmap content. Then, use
the BitmapImage to set the ImageSource property of theImageBrush. Finally, apply the ImageBrush to the object you
want to paint. In Extensible Application Markup Language (XAML), you can also just set theImageSource property of
the ImageBrush with the path of the image to load.
Like all Brush objects, an ImageBrush can be used to paint objects such as shapes, panels, controls, and text. The
following illustration shows some effects that can be achieved with an ImageBrush.
Objects painted by an ImageBrush
130
By default, an ImageBrush stretches its image to completely fill the area being painted, possibly distorting the image if
the painted area has a different aspect ratio than the image. You can change this behavior by changing
the Stretch property from its default value of Fill to None, Uniform, or UniformToFill. BecauseImageBrush is a type
of TileBrush, you can specify exactly how an image brush fills the output area and even create patterns. For more
information about advanced TileBrush features, see the TileBrush Overview.
Example: Paint an Object with a Bitmap Image
The following example uses an ImageBrush to paint the Background of a Canvas.
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="Microsoft.Samples.BrushExamples.ImageBrushExample" WindowTitle="ImageBrush Example" Background="White"> <StackPanel> <Canvas Height="200" Width="300"> <Canvas.Background> <ImageBrush ImageSource="sampleImages\Waterlilies.jpg" /> </Canvas.Background> </Canvas> </StackPanel> </Page>
C#
VB
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; namespace Microsoft.Samples.BrushExamples { public class ImageBrushExample : Page { public ImageBrushExample() { StackPanel mainPanel = new StackPanel(); canvasBackgroundExample(mainPanel); this.Content = mainPanel; } private void canvasBackgroundExample(Panel mainPanel) { BitmapImage theImage = new BitmapImage (new Uri("sampleImages\\Waterlilies.jpg", UriKind.Relative)); ImageBrush myImageBrush = new ImageBrush(theImage); Canvas myCanvas = new Canvas(); myCanvas.Width = 300; myCanvas.Height = 200; myCanvas.Background = myImageBrush;
131
mainPanel.Children.Add(myCanvas); } } }
Paint an Area with a Drawing
A DrawingBrush enables you to paint an area with shapes, text, images, and video. Shapes inside a drawing brush may
themselves be painted with a solid color, gradient, image, or even another DrawingBrush. The following illustration
demonstrates some uses of a DrawingBrush.
Objects painted by a DrawingBrush
A DrawingBrush paints an area with a Drawing object. A Drawing object describes visible content, such as a shape,
bitmap, video, or a line of text. Different types of drawings describe different types of content. The following is a list of
the different types of drawing objects.
GeometryDrawing – Draws a shape.
ImageDrawing – Draws an image.
GlyphRunDrawing – Draws text.
VideoDrawing – Plays an audio or video file.
DrawingGroup – Draws other drawings. Use a drawing group to combine other drawings into a single
composite drawing.
For more information about Drawing objects, see the Drawing Objects Overview.
Like an ImageBrush, a DrawingBrush stretches its Drawing to fill its output area. You can override this behavior by
changing the Stretch property from its default setting of Fill. For more information, see the Stretch property.
Example: Paint an Object with a Drawing
The following example shows how to paint an object with a drawing of three ellipses. A GeometryDrawing is used to
describe the ellipses.
132
XAML
<Button Content="A Button"> <Button.Background> <DrawingBrush> <DrawingBrush.Drawing> <GeometryDrawing Brush="LightBlue"> <GeometryDrawing.Geometry> <GeometryGroup> <EllipseGeometry RadiusX="12.5" RadiusY="25" Center="25,50" /> <EllipseGeometry RadiusX="12.5" RadiusY="25" Center="50,50" /> <EllipseGeometry RadiusX="12.5" RadiusY="25" Center="75,50" /> </GeometryGroup> </GeometryDrawing.Geometry> <GeometryDrawing.Pen> <Pen Thickness="1" Brush="Gray" /> </GeometryDrawing.Pen> </GeometryDrawing> </DrawingBrush.Drawing> </DrawingBrush> </Button.Background> </Button>
C#
VB
// Create a DrawingBrush. DrawingBrush myDrawingBrush = new DrawingBrush(); // Create a drawing. GeometryDrawing myGeometryDrawing = new GeometryDrawing(); myGeometryDrawing.Brush = Brushes.LightBlue; myGeometryDrawing.Pen = new Pen(Brushes.Gray, 1); GeometryGroup ellipses = new GeometryGroup(); ellipses.Children.Add(new EllipseGeometry(new Point(25,50), 12.5, 25)); ellipses.Children.Add(new EllipseGeometry(new Point(50,50), 12.5, 25)); ellipses.Children.Add(new EllipseGeometry(new Point(75,50), 12.5, 25)); myGeometryDrawing.Geometry = ellipses; myDrawingBrush.Drawing = myGeometryDrawing; Button myButton = new Button(); myButton.Content = "A Button"; // Use the DrawingBrush to paint the button's background. myButton.Background = myDrawingBrush;
Paint an Area with a Visual
The most versatile and powerful of all the brushes, the VisualBrush paints an area with a Visual. A Visual is a low-level
graphical type that serves as the ancestor of many useful graphical components. For example,
the Window, FrameworkElement, and Control classes are all types of Visual objects. Using a VisualBrush, you can paint
areas with almost any Windows Presentation Foundation (WPF) graphical object.
Note
133
Although VisualBrush is a type of Freezable object, it cannot be frozen (made read-only) when
its Visual property is set to a value other than null.
There are two ways to specify the Visual content of a VisualBrush.
Create a new Visual and use it to set the Visual property of the VisualBrush. For an example, see the Example:
Paint an Object with a Visual section that follows.
Use an existing Visual, which creates a duplicate image of the target Visual. You can then use the VisualBrush to
create interesting effects, such as reflection and magnification. For an example, see the Example: Create a
Reflection section.
When you define a new Visual for a VisualBrush and that Visual is a UIElement (such as a panel or control), the layout
system runs on the UIElement and its child elements when the AutoLayoutContent property is set to true. However,
the root UIElement is essentially isolated from the rest of the system: styles, and external layout can't permeate this
boundary. Therefore, you should explicitly specify the size of the root UIElement, because its only parent is
the VisualBrush and therefore it cannot automatically size itself to the area being painted. For more information about
layout in Windows Presentation Foundation (WPF), see theLayout System.
Like ImageBrush and DrawingBrush, a VisualBrush stretches its content to fill its output area. You can override this
behavior by changing the Stretch property from its default setting of Fill. For more information, see
the Stretch property.
Example: Paint an Object with a Visual
In the following example, several controls and a panel are used to paint a rectangle.
XAML
<Rectangle Width="150" Height="150" Stroke="Black" Margin="5,0,5,0"> <Rectangle.Fill> <VisualBrush> <VisualBrush.Visual> <StackPanel Background="White"> <Rectangle Width="25" Height="25" Fill="Red" Margin="2" /> <TextBlock FontSize="10pt" Margin="2">Hello, World!</TextBlock> <Button Margin="2">A Button</Button> </StackPanel> </VisualBrush.Visual> </VisualBrush> </Rectangle.Fill> </Rectangle>
C#
VB
VisualBrush myVisualBrush = new VisualBrush(); // Create the visual brush's contents. StackPanel myStackPanel = new StackPanel(); myStackPanel.Background = Brushes.White; Rectangle redRectangle = new Rectangle(); redRectangle.Width = 25;
134
redRectangle.Height =25; redRectangle.Fill = Brushes.Red; redRectangle.Margin = new Thickness(2); myStackPanel.Children.Add(redRectangle); TextBlock someText = new TextBlock(); FontSizeConverter myFontSizeConverter = new FontSizeConverter(); someText.FontSize = (double)myFontSizeConverter.ConvertFrom("10pt"); someText.Text = "Hello, World!"; someText.Margin = new Thickness(2); myStackPanel.Children.Add(someText); Button aButton = new Button(); aButton.Content = "A Button"; aButton.Margin = new Thickness(2); myStackPanel.Children.Add(aButton); // Use myStackPanel as myVisualBrush's content. myVisualBrush.Visual = myStackPanel; // Create a rectangle to paint. Rectangle myRectangle = new Rectangle(); myRectangle.Width = 150; myRectangle.Height = 150; myRectangle.Stroke = Brushes.Black; myRectangle.Margin = new Thickness(5,0,5,0); // Use myVisualBrush to paint myRectangle. myRectangle.Fill = myVisualBrush;
Example: Create a Reflection
The preceding example showed how to create a new Visual for use as a background. You can also use a VisualBrush to
display an existing visual; this capability enables you to produce interesting visual effects, such as reflections and
magnification. The following example uses a VisualBrush to create a reflection of aBorder that contains several
elements. The following illustration shows the output that this example produces.
A reflected Visual object
C#
VB
135
using System; using System.Windows; using System.Windows.Data; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.IO; using System.Collections.ObjectModel; using System.Windows.Shapes; namespace SDKSample { public partial class ReflectionExample : Page { public ReflectionExample() { // Create a name scope for the page. NameScope.SetNameScope(this, new NameScope()); this.Background = Brushes.Black; StackPanel myStackPanel = new StackPanel(); myStackPanel.Margin = new Thickness(50); Border myReflectedBorder = new Border(); this.RegisterName("ReflectedVisual", myReflectedBorder); // Create a gradient background for the border. GradientStop firstStop = new GradientStop(); firstStop.Offset = 0.0; Color firstStopColor = new Color(); firstStopColor.R = 204; firstStopColor.G = 204; firstStopColor.B = 255; firstStopColor.A = 255; firstStop.Color = firstStopColor; GradientStop secondStop = new GradientStop(); secondStop.Offset = 1.0; secondStop.Color = Colors.White; GradientStopCollection myGradientStopCollection = new GradientStopCollection(); myGradientStopCollection.Add(firstStop); myGradientStopCollection.Add(secondStop); LinearGradientBrush myLinearGradientBrush = new LinearGradientBrush(); myLinearGradientBrush.StartPoint = new Point(0, 0.5); myLinearGradientBrush.EndPoint = new Point(1, 0.5); myLinearGradientBrush.GradientStops = myGradientStopCollection; myReflectedBorder.Background = myLinearGradientBrush; // Add contents to the border. StackPanel borderStackPanel = new StackPanel(); borderStackPanel.Orientation = Orientation.Horizontal; borderStackPanel.Margin = new Thickness(10); TextBlock myTextBlock = new TextBlock(); myTextBlock.TextWrapping = TextWrapping.Wrap; myTextBlock.Width = 200; myTextBlock.Text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit." + " Suspendisse vel ante. Donec luctus tortor sit amet est." + " Nullam pulvinar odio et wisi." + " Pellentesque quis magna. Sed pellentesque." + " Nulla euismod." + "Pellentesque habitant morbi tristique senectus et netus “ + “et malesuada fames ac turpis egestas."; borderStackPanel.Children.Add(myTextBlock); StackPanel ellipseStackPanel = new StackPanel();
136
Ellipse ellipse1 = new Ellipse(); ellipse1.Margin = new Thickness(10); ellipse1.Height = 50; ellipse1.Width = 50; ellipse1.Fill = Brushes.Black; ellipseStackPanel.Children.Add(ellipse1); Ellipse ellipse2 = new Ellipse(); ellipse2.Margin = new Thickness(10); ellipse2.Height = 50; ellipse2.Width = 50; ellipse2.Fill = Brushes.Black; ellipseStackPanel.Children.Add(ellipse2); Ellipse ellipse3 = new Ellipse(); ellipse3.Margin = new Thickness(10); ellipse3.Height = 50; ellipse3.Width = 50; ellipse3.Fill = Brushes.Black; ellipseStackPanel.Children.Add(ellipse3); borderStackPanel.Children.Add(ellipseStackPanel); myReflectedBorder.Child = borderStackPanel; // Create divider rectangle Rectangle dividerRectangle = new Rectangle(); dividerRectangle.Height = 1; dividerRectangle.Fill = Brushes.Gray; dividerRectangle.HorizontalAlignment = HorizontalAlignment.Stretch; // Create the object to contain the reflection. Rectangle reflectionRectangle = new Rectangle(); // Bind the height of the rectangle to the border height. Binding heightBinding = new Binding(); heightBinding.ElementName = "ReflectedVisual"; heightBinding.Path = new PropertyPath(Rectangle.HeightProperty); BindingOperations.SetBinding( reflectionRectangle, Rectangle.HeightProperty, heightBinding); // Bind the width of the rectangle to the border width. Binding widthBinding = new Binding(); widthBinding.ElementName = "ReflectedVisual"; widthBinding.Path = new PropertyPath(Rectangle.WidthProperty); BindingOperations.SetBinding( reflectionRectangle, Rectangle.WidthProperty, widthBinding); // Creates the reflection. VisualBrush myVisualBrush = new VisualBrush(); myVisualBrush.Opacity = 0.75; myVisualBrush.Stretch = Stretch.None; Binding reflectionBinding = new Binding(); reflectionBinding.ElementName = "ReflectedVisual"; BindingOperations.SetBinding( myVisualBrush, VisualBrush.VisualProperty, reflectionBinding); ScaleTransform myScaleTransform = new ScaleTransform(); myScaleTransform.ScaleX = 1; myScaleTransform.ScaleY = -1; TranslateTransform myTranslateTransform = new TranslateTransform(); myTranslateTransform.Y = 1; TransformGroup myTransformGroup = new TransformGroup(); myTransformGroup.Children.Add(myScaleTransform); myTransformGroup.Children.Add(myTranslateTransform); myVisualBrush.RelativeTransform = myTransformGroup; reflectionRectangle.Fill = myVisualBrush; // Create a gradient background for the border.
137
GradientStop firstStop2 = new GradientStop(); firstStop2.Offset = 0.0; Color c1 = new Color(); c1.R = 0; c1.G = 0; c1.B = 0; c1.A = 255; firstStop2.Color = c1; GradientStop secondStop2 = new GradientStop(); secondStop2.Offset = 0.5; Color c2 = new Color(); c2.R = 0; c2.G = 0; c2.B = 0; c2.A = 51; firstStop2.Color = c2; GradientStop thirdStop = new GradientStop(); thirdStop.Offset = 0.75; Color c3 = new Color(); c3.R = 0; c3.G = 0; c3.B = 0; c3.A = 0; thirdStop.Color = c3; GradientStopCollection myGradientStopCollection2 = new GradientStopCollection(); myGradientStopCollection2.Add(firstStop2); myGradientStopCollection2.Add(secondStop2); myGradientStopCollection2.Add(thirdStop); LinearGradientBrush myLinearGradientBrush2 = new LinearGradientBrush(); myLinearGradientBrush2.StartPoint = new Point(0.5, 0); myLinearGradientBrush2.EndPoint = new Point(0.5, 1); myLinearGradientBrush2.GradientStops = myGradientStopCollection2; reflectionRectangle.OpacityMask = myLinearGradientBrush2; BlurBitmapEffect myBlurBitmapEffect = new BlurBitmapEffect(); myBlurBitmapEffect.Radius = 1.5; reflectionRectangle.BitmapEffect = myBlurBitmapEffect; myStackPanel.Children.Add(myReflectedBorder); myStackPanel.Children.Add(dividerRectangle); myStackPanel.Children.Add(reflectionRectangle); this.Content = myStackPanel; } /* <Rectangle Height="{Binding Path=ActualHeight, ElementName=ReflectedVisual}" Width="{Binding Path=ActualWidth, ElementName=ReflectedVisual}"> <Rectangle.OpacityMask> <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1"> <GradientStop Color="#FF000000" Offset="0.0" /> <GradientStop Color="#33000000" Offset="0.5" /> <GradientStop Color="#00000000" Offset="0.75" /> </LinearGradientBrush> </Rectangle.OpacityMask> <Rectangle.BitmapEffect> <BlurBitmapEffect Radius="1.5" /> </Rectangle.BitmapEffect> </Rectangle> </StackPanel> </Page> */
138
} }
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="Black"> <StackPanel Margin="50"> <!-- The object to reflect. --> <Border Name="ReflectedVisual" Width="400"> <Border.Background> <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5"> <GradientStop Offset="0.0" Color="#CCCCFF" /> <GradientStop Offset="1.0" Color="White" /> </LinearGradientBrush> </Border.Background> <StackPanel Orientation="Horizontal" Margin="10"> <TextBlock TextWrapping="Wrap" Width="200" Margin="10"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse vel ante. Donec luctus tortor sit amet est. Nullam pulvinar odio et wisi. Pellentesque quis magna. Sed pellentesque. Nulla euismod. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. </TextBlock> <StackPanel> <Ellipse Margin="10" Height="50" Width="50" Fill="Black" /> <Ellipse Margin="10" Height="50" Width="50" Fill="Black" /> <Ellipse Margin="10" Height="50" Width="50" Fill="Black" /> </StackPanel> </StackPanel> </Border> <Rectangle Height="1" Fill="Gray" HorizontalAlignment="Stretch" /> <!-- The object to contain the reflection.--> <Rectangle Height="{Binding Path=ActualHeight, ElementName=ReflectedVisual}" Width="{Binding Path=ActualWidth, ElementName=ReflectedVisual}"> <Rectangle.Fill> <!-- Creates the reflection. --> <VisualBrush Opacity="0.75" Stretch="None" Visual="{Binding ElementName=ReflectedVisual}"> <VisualBrush.RelativeTransform> <!-- Flip the reflection. --> <TransformGroup> <ScaleTransform ScaleX="1" ScaleY="-1" /> <TranslateTransform Y="1" /> </TransformGroup> </VisualBrush.RelativeTransform> </VisualBrush> </Rectangle.Fill> <Rectangle.OpacityMask>
139
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1"> <GradientStop Color="#FF000000" Offset="0.0" /> <GradientStop Color="#33000000" Offset="0.5" /> <GradientStop Color="#00000000" Offset="0.75" /> </LinearGradientBrush> </Rectangle.OpacityMask> <Rectangle.BitmapEffect> <BlurBitmapEffect Radius="1.5" /> </Rectangle.BitmapEffect> </Rectangle> </StackPanel> </Page>
For additional examples that show how to magnify portions of the screen and how to create reflections, see
the VisualBrush Sample.
TileBrush Features
ImageBrush , DrawingBrush, and VisualBrush are types of TileBrush objects. TileBrush objects provide you with a great
deal of control over how an area is painted with an image, drawing, or visual. For example, instead of just painting an
area with a single stretched image, you can paint an area with a series of image tiles that create a pattern.
A TileBrush has three primary components: content, tiles, and the output area.
Components of a TileBrush with a single tile
Components of a TileBrush with multiple tiles
140
For more information about the tiling features of TileBrush objects, see the TileBrush Overview.
See Also
Reference
ImageBrush
DrawingBrush
VisualBrush
TileBrush
Concepts
TileBrush Overview
WPF Brushes Overview
Imaging Overview
Drawing Objects Overview
Opacity Masks Overview
WPF Graphics Rendering Overview
Other Resources
ImageBrush Sample
VisualBrush Sample
141
Path Class .NET Framework 4
Draws a series of connected lines and curves.
Inheritance Hierarchy
System.Object
System.Windows.Threading.DispatcherObject
System.Windows.DependencyObject
System.Windows.Media.Visual
System.Windows.UIElement
System.Windows.FrameworkElement
System.Windows.Shapes.Shape
System.Windows.Shapes.Path
Namespace: System.Windows.Shapes
Assembly: PresentationFramework (in PresentationFramework.dll)
XMLNS for XAML: http://schemas.microsoft.com/winfx/2006/xaml/presentation,
http://schemas.microsoft.com/netfx/2007/xaml/presentation
Syntax
C#
C++
F#
VB
public sealed class Path : Shape
XAML Object Element Usage
<Path .../>
The Path type exposes the following members.
Constructors
Name Description
Path Initializes a new instance of the Path class.
Top
142
Properties
Name Description
ActualHeight Gets the rendered height of this element. (Inherited from FrameworkElement.)
ActualWidth Gets the rendered width of this element. (Inherited from FrameworkElement.)
AllowDrop Gets or sets a value indicating whether this element can be used as the target of a drag-and-drop operation. This is a dependency property. (Inherited from UIElement.)
AreAnyTouchesCaptured
Gets a value that indicates whether at least one touch is captured to this element. (Inherited from UIElement.)
AreAnyTouchesCapturedWithin
Gets a value that indicates whether at least one touch is captured to this element or to any child elements in its visual tree. (Inherited from UIElement.)
AreAnyTouchesDirectlyOver
Gets a value that indicates whether at least one touch is pressed over this element. (Inherited from UIElement.)
AreAnyTouchesOver Gets a value that indicates whether at least one touch is pressed over this element or any child elements in its visual tree. (Inherited from UIElement.)
BindingGroup Gets or sets the BindingGroup that is used for the element. (Inherited from FrameworkElement.)
BitmapEffect Obsolete. Gets or sets a bitmap effect that applies directly to the rendered content for this element. This is a dependency property. (Inherited from UIElement.)
BitmapEffectInput Obsolete. Gets or sets an input source for the bitmap effect that applies directly to the rendered content for this element. This is a dependency property. (Inherited from UIElement.)
CacheMode Gets or sets a cached representation of the UIElement. (Inherited from UIElement.)
Clip Gets or sets the geometry used to define the outline of the contents of an element. This is a dependency property. (Inherited from UIElement.)
ClipToBounds Gets or sets a value indicating whether to clip the content of this element (or content coming from the child elements of this element) to fit into the size of the containing element. This is a dependency property. (Inherited from UIElement.)
CommandBindings Gets a collection of CommandBinding objects associated with this element. A CommandBinding enables command handling for this element, and declares the linkage between a command, its events, and the handlers attached by this element. (Inherited from UIElement.)
ContextMenu Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element. (Inherited from FrameworkElement.)
143
Cursor Gets or sets the cursor that displays when the mouse pointer is over this element. (Inherited fromFrameworkElement.)
Data Gets or sets a Geometry that specifies the shape to be drawn.
DataContext Gets or sets the data context for an element when it participates in data binding. (Inherited fromFrameworkElement.)
DefaultStyleKey Gets or sets the key to use to reference the style for this control, when theme styles are used or defined.(Inherited from FrameworkElement.)
DefiningGeometry Gets a value that represents the Geometry of the Shape. (Inherited from Shape.)
DependencyObjectType Gets the DependencyObjectType that wraps the CLR type of this instance. (Inherited from DependencyObject.)
DesiredSize Gets the size that this element computed during the measure pass of the layout process. (Inherited fromUIElement.)
Dispatcher Gets the Dispatcher this DispatcherObject is associated with. (Inherited from DispatcherObject.)
Effect Gets or sets the bitmap effect to apply to the UIElement. This is a dependency property. (Inherited fromUIElement.)
Fill Gets or sets the Brush that specifies how the shape's interior is painted. (Inherited from Shape.)
FlowDirection Gets or sets the direction that text and other user interface (UI) elements flow within any parent element that controls their layout. (Inherited from FrameworkElement.)
Focusable Gets or sets a value that indicates whether the element can receive focus. This is a dependency property.(Inherited from UIElement.)
FocusVisualStyle Gets or sets a property that enables customization of appearance, effects, or other style characteristics that will apply to this element when it captures keyboard focus. (Inherited from FrameworkElement.)
ForceCursor Gets or sets a value that indicates whether this FrameworkElement should force the user interface (UI) to render the cursor as declared by the Cursor property. (Inherited from FrameworkElement.)
GeometryTransform Gets a value that represents a Transform that is applied to the geometry of a Shape prior to when it is drawn.(Inherited from Shape.)
HasAnimatedProperties Gets a value indicating whether this element has any animated properties. (Inherited from UIElement.)
Height Gets or sets the suggested height of the element. (Inherited from FrameworkElement.)
HorizontalAlignment Gets or sets the horizontal alignment characteristics applied to this element when it is composed within a parent element, such as a panel or items control. (Inherited
144
from FrameworkElement.)
InheritanceBehavior Gets or sets the scope limits for property value inheritance, resource key lookup, and RelativeSource FindAncestor lookup. (Inherited from FrameworkElement.)
InputBindings Gets the collection of input bindings associated with this element. (Inherited from UIElement.)
InputScope Gets or sets the context for input used by this FrameworkElement. (Inherited from FrameworkElement.)
IsArrangeValid Gets a value indicating whether the computed size and position of child elements in this element's layout are valid. (Inherited from UIElement.)
IsEnabled Gets or sets a value indicating whether this element is enabled in the user interface (UI). This is a dependency property. (Inherited from UIElement.)
IsEnabledCore Gets a value that becomes the return value of IsEnabled in derived classes. (Inherited from UIElement.)
IsFocused Gets a value that determines whether this element has logical focus. This is a dependency property. (Inherited from UIElement.)
IsHitTestVisible Gets or sets a value that declares whether this element can possibly be returned as a hit test result from some portion of its rendered content. This is a dependency property. (Inherited from UIElement.)
IsInitialized Gets a value that indicates whether this element has been initialized, either during processing by a XAML processor, or by explicitly having its EndInit method called. (Inherited from FrameworkElement.)
IsInputMethodEnabled Gets a value indicating whether an input method system, such as an Input Method Editor (IME), is enabled for processing the input to this element. (Inherited from UIElement.)
IsKeyboardFocused Gets a value indicating whether this element has keyboard focus. This is a dependency property. (Inherited fromUIElement.)
IsKeyboardFocusWithin Gets a value indicating whether keyboard focus is anywhere within the element or its visual tree child elements. This is a dependency property. (Inherited from UIElement.)
IsLoaded Gets a value that indicates whether this element has been loaded for presentation. (Inherited fromFrameworkElement.)
IsManipulationEnabled Gets or sets a value that indicates whether manipulation events are enabled on this UIElement. (Inherited fromUIElement.)
IsMeasureValid Gets a value indicating whether the current size returned by layout measure is valid. (Inherited from UIElement.)
IsMouseCaptured Gets a value indicating whether the mouse is captured to this element. This is a dependency property. (Inherited from UIElement.)
IsMouseCaptureWithin Gets a value that determines whether mouse capture is held by this element or by child
145
elements in its visual tree. This is a dependency property. (Inherited from UIElement.)
IsMouseDirectlyOver Gets a value that indicates whether the position of the mouse pointer corresponds to hit test results, which take element compositing into account. This is a dependency property. (Inherited from UIElement.)
IsMouseOver Gets a value indicating whether the mouse pointer is located over this element (including child elements in the visual tree). This is a dependency property. (Inherited from UIElement.)
IsSealed Gets a value that indicates whether this instance is currently sealed (read-only). (Inherited fromDependencyObject.)
IsStylusCaptured Gets a value indicating whether the stylus is captured by this element. This is a dependency property. (Inherited from UIElement.)
IsStylusCaptureWithin Gets a value that determines whether stylus capture is held by this element, or an element within the element bounds and its visual tree. This is a dependency property. (Inherited from UIElement.)
IsStylusDirectlyOver Gets a value that indicates whether the stylus position corresponds to hit test results, which take element compositing into account. This is a dependency property. (Inherited from UIElement.)
IsStylusOver Gets a value indicating whether the stylus cursor is located over this element (including visual child elements). This is a dependency property. (Inherited from UIElement.)
IsVisible Gets a value indicating whether this element is visible in the user interface (UI). This is a dependency property.(Inherited from UIElement.)
Language Gets or sets localization/globalization language information that applies to an element. (Inherited fromFrameworkElement.)
LayoutTransform Gets or sets a graphics transformation that should apply to this element when layout is performed. (Inherited from FrameworkElement.)
LogicalChildren Gets an enumerator for logical child elements of this element. (Inherited from FrameworkElement.)
Margin Gets or sets the outer margin of an element. (Inherited from FrameworkElement.)
MaxHeight Gets or sets the maximum height constraint of the element. (Inherited from FrameworkElement.)
MaxWidth Gets or sets the maximum width constraint of the element. (Inherited from FrameworkElement.)
MinHeight Gets or sets the minimum height constraint of the element. (Inherited from FrameworkElement.)
MinWidth Gets or sets the minimum width constraint of the element. (Inherited from FrameworkElement.)
146
Name Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.)
Opacity Gets or sets the opacity factor applied to the entire UIElement when it is rendered in the user interface (UI). This is a dependency property. (Inherited from UIElement.)
OpacityMask Gets or sets an opacity mask, as a Brush implementation that is applied to any alpha-channel masking for the rendered content of this element. This is a dependency property. (Inherited from UIElement.)
OverridesDefaultStyle Gets or sets a value that indicates whether this element incorporates style properties from theme styles.(Inherited from FrameworkElement.)
Parent Gets the logical parent element of this element. (Inherited from FrameworkElement.)
PersistId Obsolete. Gets a value that uniquely identifies this element. (Inherited from UIElement.)
RenderedGeometry Gets a value that represents the final rendered Geometry of a Shape. (Inherited from Shape.)
RenderSize Gets (or sets, but see Remarks) the final render size of this element. (Inherited from UIElement.)
RenderTransform Gets or sets transform information that affects the rendering position of this element. This is a dependency property. (Inherited from UIElement.)
RenderTransformOrigin Gets or sets the center point of any possible render transform declared by RenderTransform, relative to the bounds of the element. This is a dependency property. (Inherited from UIElement.)
Resources Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.)
SnapsToDevicePixels Gets or sets a value that determines whether rendering for this element should use device-specific pixel settings during rendering. This is a dependency property. (Inherited from UIElement.)
Stretch Gets or sets a Stretch enumeration value that describes how the shape fills its allocated space. (Inherited fromShape.)
Stroke Gets or sets the Brush that specifies how the Shape outline is painted. (Inherited from Shape.)
StrokeDashArray Gets or sets a collection of Double values that indicate the pattern of dashes and gaps that is used to outline shapes. (Inherited from Shape.)
StrokeDashCap Gets or sets a PenLineCap enumeration value that specifies how the ends of a dash are drawn. (Inherited fromShape.)
StrokeDashOffset Gets or sets a Double that specifies the distance within the dash pattern where a dash begins. (Inherited fromShape.)
147
StrokeEndLineCap Gets or sets a PenLineCap enumeration value that describes the Shape at the end of a line. (Inherited fromShape.)
StrokeLineJoin Gets or sets a PenLineJoin enumeration value that specifies the type of join that is used at the vertices of aShape. (Inherited from Shape.)
StrokeMiterLimit Gets or sets a limit on the ratio of the miter length to half the StrokeThickness of a Shape element. (Inherited from Shape.)
StrokeStartLineCap Gets or sets a PenLineCap enumeration value that describes the Shape at the start of a Stroke. (Inherited fromShape.)
StrokeThickness Gets or sets the width of the Shape outline. (Inherited from Shape.)
Style Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.)
StylusPlugIns Gets a collection of all stylus plug-in (customization) objects associated with this element. (Inherited fromUIElement.)
Tag Gets or sets an arbitrary object value that can be used to store custom information about this element. (Inherited from FrameworkElement.)
TemplatedParent Gets a reference to the template parent of this element. This property is not relevant if the element was not created through a template. (Inherited from FrameworkElement.)
ToolTip Gets or sets the tool-tip object that is displayed for this element in the user interface (UI). (Inherited fromFrameworkElement.)
TouchesCaptured Gets all touch devices that are captured to this element. (Inherited from UIElement.)
TouchesCapturedWithin Gets all touch devices that are captured to this element or any child elements in its visual tree. (Inherited fromUIElement.)
TouchesDirectlyOver Gets all touch devices that are over this element. (Inherited from UIElement.)
TouchesOver Gets all touch devices that are over this element or any child elements in its visual tree. (Inherited fromUIElement.)
Triggers Gets the collection of triggers established directly on this element, or in child elements. (Inherited fromFrameworkElement.)
Uid Gets or sets the unique identifier (for localization) for this element. This is a dependency property. (Inherited from UIElement.)
UseLayoutRounding Gets or sets a value that indicates whether layout rounding should be applied to this element's size and position during layout. (Inherited from FrameworkElement.)
VerticalAlignment Gets or sets the vertical alignment characteristics applied to this element when it is composed within a parent element such as a panel or items control. (Inherited from FrameworkElement.)
148
Visibility Gets or sets the user interface (UI) visibility of this element. This is a dependency property. (Inherited fromUIElement.)
VisualBitmapEffect Obsolete. Gets or sets the BitmapEffect value for the Visual. (Inherited from Visual.)
VisualBitmapEffectInput Obsolete. Gets or sets the BitmapEffectInput value for the Visual. (Inherited from Visual.)
VisualBitmapScalingMode
Gets or sets the BitmapScalingMode for the Visual. (Inherited from Visual.)
VisualCacheMode Gets or sets a cached representation of the Visual. (Inherited from Visual.)
VisualChildrenCount Gets the number of visual child elements within this element. (Inherited from FrameworkElement.)
VisualClearTypeHint Gets or sets the ClearTypeHint that determines how ClearType is rendered in the Visual. (Inherited from Visual.)
VisualClip Gets or sets the clip region of the Visual as a Geometry value. (Inherited from Visual.)
VisualEdgeMode Gets or sets the edge mode of the Visual as an EdgeMode value. (Inherited from Visual.)
VisualEffect Gets or sets the bitmap effect to apply to the Visual. (Inherited from Visual.)
VisualOffset Gets or sets the offset value of the visual object. (Inherited from Visual.)
VisualOpacity Gets or sets the opacity of the Visual. (Inherited from Visual.)
VisualOpacityMask Gets or sets the Brush value that represents the opacity mask of the Visual. (Inherited from Visual.)
VisualParent Gets the visual tree parent of the visual object. (Inherited from Visual.)
VisualScrollableAreaClip Gets or sets a clipped scrollable area for the Visual. (Inherited from Visual.)
VisualTextHintingMode Gets or sets the TextHintingMode of the Visual. (Inherited from Visual.)
VisualTextRenderingMode
Gets or sets the TextRenderingMode of the Visual. (Inherited from Visual.)
VisualTransform Gets or sets the Transform value for the Visual. (Inherited from Visual.)
VisualXSnappingGuidelines
Gets or sets the x-coordinate (vertical) guideline collection. (Inherited from Visual.)
VisualYSnappingGuidelines
Gets or sets the y-coordinate (horizontal) guideline collection. (Inherited from Visual.)
Width Gets or sets the width of the element. (Inherited from FrameworkElement.)
Top
Methods
149
Name Description
AddHandler(RoutedEvent, Delegate)
Adds a routed event handler for a specified routed event, adding the handler to the handler collection on the current element. (Inherited from UIElement.)
AddHandler(RoutedEvent, Delegate, Boolean)
Adds a routed event handler for a specified routed event, adding the handler to the handler collection on the current element. Specify handledEventsToo as true to have the provided handler be invoked for routed event that had already been marked as handled by another element along the event route. (Inherited from UIElement.)
AddLogicalChild Adds the provided object to the logical tree of this element. (Inherited from FrameworkElement.)
AddToEventRoute Adds handlers to the specified EventRoute for the current UIElement event handler collection.(Inherited from UIElement.)
AddVisualChild Defines the parent-child relationship between two visuals. (Inherited from Visual.)
ApplyAnimationClock(DependencyProperty, AnimationClock)
Applies an animation to a specified dependency property on this element. Any existing animations are stopped and replaced with the new animation. (Inherited from UIElement.)
ApplyAnimationClock(DependencyProperty, AnimationClock, HandoffBehavior)
Applies an animation to a specified dependency property on this element, with the ability to specify what happens if the property already has a running animation. (Inherited from UIElement.)
ApplyTemplate Builds the current template's visual tree if necessary, and returns a value that indicates whether the visual tree was rebuilt by this call. (Inherited from FrameworkElement.)
Arrange Positions child elements and determines a size for a UIElement. Parent elements call this method from their ArrangeCore implementation (or a WPF framework-level equivalent) to form a recursive layout update. This method constitutes the second pass of a layout update. (Inherited fromUIElement.)
ArrangeCore Implements ArrangeCore (defined as virtual in UIElement) and seals the implementation. (Inherited from FrameworkElement.)
ArrangeOverride Arranges a Shape by evaluating its RenderedGeometry and Stretch properties. (Inherited fromShape.)
BeginAnimation(DependencyProperty, AnimationTimeline)
Starts an animation for a specified animated property on this element. (Inherited from UIElement.)
BeginAnimation(DependencyProperty, AnimationTimeline, HandoffBehavior)
Starts a specific animation for a specified animated property on this element, with the option of specifying what happens if the property already has a running animation. (Inherited from UIElement.)
150
BeginInit Starts the initialization process for this element. (Inherited from FrameworkElement.)
BeginStoryboard(Storyboard)
Begins the sequence of actions that are contained in the provided storyboard. (Inherited fromFrameworkElement.)
BeginStoryboard(Storyboard, HandoffBehavior)
Begins the sequence of actions contained in the provided storyboard, with options specified for what should happen if the property is already animated. (Inherited from FrameworkElement.)
BeginStoryboard(Storyboard, HandoffBehavior, Boolean)
Begins the sequence of actions contained in the provided storyboard, with specified state for control of the animation after it is started. (Inherited from FrameworkElement.)
BringIntoView() Attempts to bring this element into view, within any scrollable regions it is contained within. (Inherited from FrameworkElement.)
BringIntoView(Rect) Attempts to bring the provided region size of this element into view, within any scrollable regions it is contained within. (Inherited from FrameworkElement.)
CaptureMouse Attempts to force capture of the mouse to this element. (Inherited from UIElement.)
CaptureStylus Attempts to force capture of the stylus to this element. (Inherited from UIElement.)
CaptureTouch Attempts to force capture of a touch to this element. (Inherited from UIElement.)
CheckAccess Determines whether the calling thread has access to this DispatcherObject. (Inherited fromDispatcherObject.)
ClearValue(DependencyProperty)
Clears the local value of a property. The property to be cleared is specified by aDependencyProperty identifier. (Inherited from DependencyObject.)
ClearValue(DependencyPropertyKey)
Clears the local value of a read-only property. The property to be cleared is specified by aDependencyPropertyKey. (Inherited from DependencyObject.)
CoerceValue Coerces the value of the specified dependency property. This is accomplished by invoking anyCoerceValueCallback function specified in property metadata for the dependency property as it exists on the calling DependencyObject. (Inherited from DependencyObject.)
EndInit Indicates that the initialization process for the element is complete. (Inherited fromFrameworkElement.)
Equals Determines whether a provided DependencyObject is equivalent to the current DependencyObject.(Inherited from DependencyObject.)
Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
FindCommonVisualAncestor
Returns the common ancestor of two visual objects. (Inherited from Visual.)
FindName Finds an element that has the provided identifier name. (Inherited
151
from FrameworkElement.)
FindResource Searches for a resource with the specified key, and throws an exception if the requested resource is not found. (Inherited from FrameworkElement.)
Focus Attempts to set focus to this element. (Inherited from UIElement.)
GetAnimationBaseValue
Returns the base property value for the specified property on this element, disregarding any possible animated value from a running or stopped animation. (Inherited from UIElement.)
GetBindingExpression Returns the BindingExpression that represents the binding on the specified property. (Inherited fromFrameworkElement.)
GetHashCode Gets a hash code for this DependencyObject. (Inherited from DependencyObject.)
GetLayoutClip Returns a geometry for a clipping mask. The mask applies if the layout system attempts to arrange an element that is larger than the available display space. (Inherited from FrameworkElement.)
GetLocalValueEnumerator
Creates a specialized enumerator for determining which dependency properties have locally set values on this DependencyObject. (Inherited from DependencyObject.)
GetTemplateChild Returns the named element in the visual tree of an instantiated ControlTemplate. (Inherited fromFrameworkElement.)
GetType Gets the Type of the current instance. (Inherited from Object.)
GetUIParentCore Returns an alternative logical parent for this element if there is no visual parent. (Inherited fromFrameworkElement.)
GetValue Returns the current effective value of a dependency property on this instance of aDependencyObject. (Inherited from DependencyObject.)
GetVisualChild Overrides Visual.GetVisualChild, and returns a child at the specified index from a collection of child elements. (Inherited from FrameworkElement.)
HitTestCore(GeometryHitTestParameters)
Implements Visual.HitTestCore to supply base element hit testing behavior (returningGeometryHitTestResult). (Inherited from UIElement.)
HitTestCore(PointHitTestParameters)
Implements HitTestCore to supply base element hit testing behavior (returning HitTestResult).(Inherited from UIElement.)
InputHitTest Returns the input element within the current element that is at the specified coordinates, relative to the current element's origin. (Inherited from UIElement.)
InvalidateArrange Invalidates the arrange state (layout) for the element. After the invalidation, the element will have its layout updated, which will occur asynchronously unless subsequently forced by UpdateLayout.(Inherited from UIElement.)
InvalidateMeasure Invalidates the measurement state (layout) for the element. (Inherited from UIElement.)
152
InvalidateProperty Re-evaluates the effective value for the specified dependency property (Inherited fromDependencyObject.)
InvalidateVisual Invalidates the rendering of the element, and forces a complete new layout pass. OnRender is called after the layout cycle is completed. (Inherited from UIElement.)
IsAncestorOf Determines whether the visual object is an ancestor of the descendant visual object. (Inherited fromVisual.)
IsDescendantOf Determines whether the visual object is a descendant of the ancestor visual object. (Inherited fromVisual.)
Measure Updates the DesiredSize of a UIElement. Parent elements call this method from their ownMeasureCore implementations to form a recursive layout update. Calling this method constitutes the first pass (the "Measure" pass) of a layout update. (Inherited from UIElement.)
MeasureCore Implements basic measure-pass layout system behavior for FrameworkElement. (Inherited fromFrameworkElement.)
MeasureOverride Measures a Shape during the first layout pass prior to arranging it. (Inherited from Shape.)
MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
MoveFocus Moves the keyboard focus away from this element and to another element in a provided traversal direction. (Inherited from FrameworkElement.)
OnAccessKey Provides class handling for when an access key that is meaningful for this element is invoked.(Inherited from UIElement.)
OnApplyTemplate When overridden in a derived class, is invoked whenever application code or internal processes callApplyTemplate. (Inherited from FrameworkElement.)
OnChildDesiredSizeChanged
Supports layout behavior when a child element is resized. (Inherited from UIElement.)
OnContextMenuClosing Invoked whenever an unhandled ContextMenuClosing routed event reaches this class in its route. Implement this method to add class handling for this event. (Inherited from FrameworkElement.)
OnContextMenuOpening
Invoked whenever an unhandled ContextMenuOpening routed event reaches this class in its route. Implement this method to add class handling for this event. (Inherited from FrameworkElement.)
OnCreateAutomationPeer
Returns class-specific AutomationPeer implementations for the Windows Presentation Foundation (WPF) infrastructure. (Inherited from UIElement.)
OnDragEnter Invoked when an unhandled DragDrop.DragEnter attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnDragLeave Invoked when an unhandled DragDrop.DragLeave attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for
153
this event. (Inherited from UIElement.)
OnDragOver Invoked when an unhandled DragDrop.DragOver attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnDrop Invoked when an unhandled DragDrop.DragEnter attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnGiveFeedback Invoked when an unhandled DragDrop.GiveFeedback attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnGotFocus Invoked whenever an unhandled GotFocus event reaches this element in its route. (Inherited fromFrameworkElement.)
OnGotKeyboardFocus Invoked when an unhandled Keyboard.GotKeyboardFocus attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnGotMouseCapture Invoked when an unhandled Mouse.GotMouseCapture attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnGotStylusCapture Invoked when an unhandled Stylus.GotStylusCapture attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnGotTouchCapture Provides class handling for the GotTouchCapture routed event that occurs when a touch is captured to this element. (Inherited from UIElement.)
OnInitialized Raises the Initialized event. This method is invoked whenever IsInitialized is set to true internally.(Inherited from FrameworkElement.)
OnIsKeyboardFocusedChanged
Invoked when an unhandled IsKeyboardFocusedChanged event is raised on this element. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnIsKeyboardFocusWithinChanged
Invoked just before the IsKeyboardFocusWithinChanged event is raised by this element. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnIsMouseCapturedChanged
Invoked when an unhandled IsMouseCapturedChanged event is raised on this element. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnIsMouseCaptureWithinChanged
Invoked when an unhandled IsMouseCaptureWithinChanged event is raised on this element. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnIsMouseDirectlyOverChanged
Invoked when an unhandled IsMouseDirectlyOverChanged event is raised on this element. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnIsStylusCapturedCha Invoked when an unhandled IsStylusCapturedChanged event is raised on this element.
154
nged Implement this method to add class handling for this event. (Inherited from UIElement.)
OnIsStylusCaptureWithinChanged
Invoked when an unhandled IsStylusCaptureWithinChanged event is raised on this element. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnIsStylusDirectlyOverChanged
Invoked when an unhandled IsStylusDirectlyOverChanged event is raised on this element. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnKeyDown Invoked when an unhandled Keyboard.KeyDown attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnKeyUp Invoked when an unhandled Keyboard.KeyUp attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited fromUIElement.)
OnLostFocus Raises the LostFocus routed event by using the event data that is provided. (Inherited fromUIElement.)
OnLostKeyboardFocus Invoked when an unhandled Keyboard.LostKeyboardFocus attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnLostMouseCapture Invoked when an unhandled Mouse.LostMouseCapture attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnLostStylusCapture Invoked when an unhandled Stylus.LostStylusCapture attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnLostTouchCapture Provides class handling for the LostTouchCapture routed event that occurs when this element loses a touch capture. (Inherited from UIElement.)
OnManipulationBoundaryFeedback
Called when the ManipulationBoundaryFeedback event occurs. (Inherited from UIElement.)
OnManipulationCompleted
Called when the ManipulationCompleted event occurs. (Inherited from UIElement.)
OnManipulationDelta Called when the ManipulationDelta event occurs. (Inherited from UIElement.)
OnManipulationInertiaStarting
Called when the ManipulationInertiaStarting event occurs. (Inherited from UIElement.)
OnManipulationStarted Called when the ManipulationStarted event occurs. (Inherited from UIElement.)
OnManipulationStarting Provides class handling for the ManipulationStarting routed event that occurs when the manipulation processor is first created. (Inherited from UIElement.)
OnMouseDown Invoked when an unhandled Mouse.MouseDown attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for
155
this event. (Inherited from UIElement.)
OnMouseEnter Invoked when an unhandled Mouse.MouseEnter attached event is raised on this element. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnMouseLeave Invoked when an unhandled Mouse.MouseLeave attached event is raised on this element. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnMouseLeftButtonDown
Invoked when an unhandled MouseLeftButtonDown routed event is raised on this element. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnMouseLeftButtonUp Invoked when an unhandled MouseLeftButtonUp routed event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited fromUIElement.)
OnMouseMove Invoked when an unhandled Mouse.MouseMove attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnMouseRightButtonDown
Invoked when an unhandled MouseRightButtonDown routed event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnMouseRightButtonUp
Invoked when an unhandled MouseRightButtonUp routed event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnMouseUp Invoked when an unhandled Mouse.MouseUp routed event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited fromUIElement.)
OnMouseWheel Invoked when an unhandled Mouse.MouseWheel attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnPreviewDragEnter Invoked when an unhandled DragDrop.PreviewDragEnter attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewDragLeave Invoked when an unhandled DragDrop.PreviewDragLeave attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewDragOver Invoked when an unhandled DragDrop.PreviewDragOver attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewDrop Invoked when an unhandled DragDrop.PreviewDrop attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
156
OnPreviewGiveFeedback
Invoked when an unhandled DragDrop.PreviewGiveFeedback attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewGotKeyboardFocus
Invoked when an unhandled Keyboard.PreviewGotKeyboardFocus attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnPreviewKeyDown Invoked when an unhandled Keyboard.PreviewKeyDown attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewKeyUp Invoked when an unhandled Keyboard.PreviewKeyUp attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnPreviewLostKeyboardFocus
Invoked when an unhandled Keyboard.PreviewKeyDown attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewMouseDown Invoked when an unhandled Mouse.PreviewMouseDown attached routed event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnPreviewMouseLeftButtonDown
Invoked when an unhandled PreviewMouseLeftButtonDown routed event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewMouseLeftButtonUp
Invoked when an unhandled PreviewMouseLeftButtonUp routed event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnPreviewMouseMove Invoked when an unhandled Mouse.PreviewMouseMove attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewMouseRightButtonDown
Invoked when an unhandled PreviewMouseRightButtonDown routed event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewMouseRightButtonUp
Invoked when an unhandled PreviewMouseRightButtonUp routed event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewMouseUp Invoked when an unhandled Mouse.PreviewMouseUp attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnPreviewMouseWheel Invoked when an unhandled Mouse.PreviewMouseWheel attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewQueryContin Invoked when an unhandled DragDrop.PreviewQueryContinueDrag attached event
157
ueDrag reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnPreviewStylusButtonDown
Invoked when an unhandled Stylus.PreviewStylusButtonDown attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewStylusButtonUp
Invoked when an unhandled Stylus.PreviewStylusButtonUp attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewStylusDown Invoked when an unhandled Stylus.PreviewStylusDown attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnPreviewStylusInAirMove
Invoked when an unhandled Stylus.PreviewStylusInAirMove attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewStylusInRange
Invoked when an unhandled Stylus.PreviewStylusInRange attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewStylusMove Invoked when an unhandled Stylus.PreviewStylusMove attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnPreviewStylusOutOfRange
Invoked when an unhandled Stylus.PreviewStylusOutOfRange attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewStylusSystemGesture
Invoked when an unhandled Stylus.PreviewStylusSystemGesture attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnPreviewStylusUp Invoked when an unhandled Stylus.PreviewStylusUp attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnPreviewTextInput Invoked when an unhandled TextCompositionManager.PreviewTextInput attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnPreviewTouchDown Provides class handling for the PreviewTouchDown routed event that occurs when a touch presses this element. (Inherited from UIElement.)
OnPreviewTouchMove Provides class handling for the PreviewTouchMove routed event that occurs when a touch moves while inside this element. (Inherited from UIElement.)
OnPreviewTouchUp Provides class handling for the PreviewTouchUp routed event that occurs when a touch is released inside this element. (Inherited from UIElement.)
OnPropertyChanged Invoked whenever the effective value of any dependency property on
158
this FrameworkElement has been updated. The specific dependency property that changed is reported in the arguments parameter. Overrides OnPropertyChanged. (Inherited from FrameworkElement.)
OnQueryContinueDrag Invoked when an unhandled DragDrop.QueryContinueDrag attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnQueryCursor Invoked when an unhandled Mouse.QueryCursor attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnRender Provides a means to change the default appearance of a Shape element. (Inherited from Shape.)
OnRenderSizeChanged Raises the SizeChanged event, using the specified information as part of the eventual event data.(Inherited from FrameworkElement.)
OnStyleChanged Invoked when the style in use on this element changes, which will invalidate the layout. (Inherited from FrameworkElement.)
OnStylusButtonDown Invoked when an unhandled Stylus.StylusButtonDown attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnStylusButtonUp Invoked when an unhandled Stylus.StylusButtonUp attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnStylusDown Invoked when an unhandled Stylus.StylusDown attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited fromUIElement.)
OnStylusEnter Invoked when an unhandled Stylus.StylusEnter attached event is raised by this element. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnStylusInAirMove Invoked when an unhandled Stylus.StylusInAirMove attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnStylusInRange Invoked when an unhandled Stylus.StylusInRange attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnStylusLeave Invoked when an unhandled Stylus.StylusLeave attached event is raised by this element. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnStylusMove Invoked when an unhandled Stylus.StylusMove attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited fromUIElement.)
OnStylusOutOfRange Invoked when an unhandled Stylus.StylusOutOfRange attached event reaches an element in its route that is derived from this class. Implement this method to add class handling
159
for this event. (Inherited from UIElement.)
OnStylusSystemGesture Invoked when an unhandled Stylus.StylusSystemGesture attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.(Inherited from UIElement.)
OnStylusUp Invoked when an unhandled Stylus.StylusUp attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited fromUIElement.)
OnTextInput Invoked when an unhandled TextCompositionManager.TextInput attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. (Inherited from UIElement.)
OnToolTipClosing Invoked whenever an unhandled ToolTipClosing routed event reaches this class in its route. Implement this method to add class handling for this event. (Inherited from FrameworkElement.)
OnToolTipOpening Invoked whenever the ToolTipOpening routed event reaches this class in its route. Implement this method to add class handling for this event. (Inherited from FrameworkElement.)
OnTouchDown Provides class handling for the TouchDown routed event that occurs when a touch presses inside this element. (Inherited from UIElement.)
OnTouchEnter Provides class handling for the TouchEnter routed event that occurs when a touch moves from outside to inside the bounds of this element. (Inherited from UIElement.)
OnTouchLeave Provides class handling for the TouchLeave routed event that occurs when a touch moves from inside to outside the bounds of this UIElement. (Inherited from UIElement.)
OnTouchMove Provides class handling for the TouchMove routed event that occurs when a touch moves while inside this element. (Inherited from UIElement.)
OnTouchUp Provides class handling for the TouchUp routed event that occurs when a touch is released inside this element. (Inherited from UIElement.)
OnVisualChildrenChanged
Called when the VisualCollection of the visual object is modified. (Inherited from Visual.)
OnVisualParentChanged Invoked when the parent of this element in the visual tree is changed. OverridesOnVisualParentChanged. (Inherited from FrameworkElement.)
ParentLayoutInvalidated
Supports incremental layout implementations in specialized subclasses of FrameworkElement.ParentLayoutInvalidated is invoked when a child element has invalidated a property that is marked in metadata as affecting the parent's measure or arrange passes during layout. (Inherited fromFrameworkElement.)
PointFromScreen Converts a Point in screen coordinates into a Point that represents the current coordinate system of the Visual. (Inherited from Visual.)
PointToScreen Converts a Point that represents the current coordinate system of the Visual into a Point in screen coordinates. (Inherited from Visual.)
160
PredictFocus Determines the next element that would receive focus relative to this element for a provided focus movement direction, but does not actually move the focus. (Inherited from FrameworkElement.)
RaiseEvent Raises a specific routed event. The RoutedEvent to be raised is identified within the RoutedEventArgsinstance that is provided (as the RoutedEvent property of that event data). (Inherited fromUIElement.)
ReadLocalValue Returns the local value of a dependency property, if it exists. (Inherited from DependencyObject.)
RegisterName Provides an accessor that simplifies access to the NameScope registration method. (Inherited fromFrameworkElement.)
ReleaseAllTouchCaptures
Releases all captured touch devices from this element. (Inherited from UIElement.)
ReleaseMouseCapture Releases the mouse capture, if this element held the capture. (Inherited from UIElement.)
ReleaseStylusCapture Releases the stylus device capture, if this element held the capture. (Inherited from UIElement.)
ReleaseTouchCapture Attempts to release the specified touch device from this element. (Inherited from UIElement.)
RemoveHandler Removes the specified routed event handler from this element. (Inherited from UIElement.)
RemoveLogicalChild Removes the provided object from this element's logical tree. FrameworkElement updates the affected logical tree parent pointers to keep in sync with this deletion. (Inherited fromFrameworkElement.)
RemoveVisualChild Removes the parent-child relationship between two visuals. (Inherited from Visual.)
SetBinding(DependencyProperty, String)
Attaches a binding to this element, based on the provided source property name as a path qualification to the data source. (Inherited from FrameworkElement.)
SetBinding(DependencyProperty, BindingBase)
Attaches a binding to this element, based on the provided binding object. (Inherited fromFrameworkElement.)
SetCurrentValue Sets the value of a dependency property without changing its value source. (Inherited fromDependencyObject.)
SetResourceReference Searches for a resource with the specified name and sets up a resource reference to it for the specified property. (Inherited from FrameworkElement.)
SetValue(DependencyProperty, Object)
Sets the local value of a dependency property, specified by its dependency property identifier.(Inherited from DependencyObject.)
SetValue(DependencyPropertyKey, Object)
Sets the local value of a read-only dependency property, specified by the DependencyPropertyKeyidentifier of the dependency property. (Inherited from DependencyObject.)
161
ShouldSerializeCommandBindings
Returns whether serialization processes should serialize the contents of the CommandBindingsproperty on instances of this class. (Inherited from UIElement.)
ShouldSerializeInputBindings
Returns whether serialization processes should serialize the contents of the InputBindings property on instances of this class. (Inherited from UIElement.)
ShouldSerializeProperty Returns a value that indicates whether serialization processes should serialize the value for the provided dependency property. (Inherited from DependencyObject.)
ShouldSerializeResources
Returns whether serialization processes should serialize the contents of the Resources property.(Inherited from FrameworkElement.)
ShouldSerializeStyle Returns whether serialization processes should serialize the contents of the Style property. (Inherited from FrameworkElement.)
ShouldSerializeTriggers Returns whether serialization processes should serialize the contents of the Triggers property.(Inherited from FrameworkElement.)
ToString Returns a string that represents the current object. (Inherited from Object.)
TransformToAncestor(Visual)
Returns a transform that can be used to transform coordinates from the Visual to the specifiedVisual ancestor of the visual object. (Inherited from Visual.)
TransformToAncestor(Visual3D)
Returns a transform that can be used to transform coordinates from the Visual to the specifiedVisual3D ancestor of the visual object. (Inherited from Visual.)
TransformToDescendant
Returns a transform that can be used to transform coordinates from the Visual to the specified visual object descendant. (Inherited from Visual.)
TransformToVisual Returns a transform that can be used to transform coordinates from the Visual to the specified visual object. (Inherited from Visual.)
TranslatePoint Translates a point relative to this element to coordinates that are relative to the specified element.(Inherited from UIElement.)
TryFindResource Searches for a resource with the specified key, and returns that resource if found. (Inherited fromFrameworkElement.)
UnregisterName Simplifies access to the NameScope de-registration method. (Inherited from FrameworkElement.)
UpdateLayout Ensures that all visual child elements of this element are properly updated for layout. (Inherited fromUIElement.)
VerifyAccess Enforces that the calling thread has access to this DispatcherObject. (Inherited fromDispatcherObject.)
Top
Events
162
Name Description
ContextMenuClosing Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.)
ContextMenuOpening Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.)
DataContextChanged Occurs when the data context for this element changes. (Inherited from FrameworkElement.)
DragEnter Occurs when the input system reports an underlying drag event with this element as the drag target. (Inherited from UIElement.)
DragLeave Occurs when the input system reports an underlying drag event with this element as the drag origin. (Inherited from UIElement.)
DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target.(Inherited from UIElement.)
Drop Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement.)
FocusableChanged Occurs when the value of the Focusable property changes. (Inherited from UIElement.)
GiveFeedback Occurs when the input system reports an underlying drag-and-drop event that involves this element. (Inherited from UIElement.)
GotFocus Occurs when this element gets logical focus. (Inherited from UIElement.)
GotKeyboardFocus Occurs when the keyboard is focused on this element. (Inherited from UIElement.)
GotMouseCapture Occurs when this element captures the mouse. (Inherited from UIElement.)
GotStylusCapture Occurs when this element captures the stylus. (Inherited from UIElement.)
GotTouchCapture Occurs when a touch is captured to this element. (Inherited from UIElement.)
Initialized Occurs when this FrameworkElement is initialized. This event coincides with cases where the value of theIsInitialized property changes from false (or undefined) to true. (Inherited from FrameworkElement.)
IsEnabledChanged Occurs when the value of the IsEnabled property on this element changes. (Inherited from UIElement.)
IsHitTestVisibleChanged Occurs when the value of the IsHitTestVisible dependency property changes on this element. (Inherited fromUIElement.)
IsKeyboardFocusedChanged
Occurs when the value of the IsKeyboardFocused property changes on this element. (Inherited from UIElement.)
IsKeyboardFocusWithin Occurs when the value of the IsKeyboardFocusWithinChanged property changes on this
163
Changed element. (Inherited from UIElement.)
IsMouseCapturedChanged
Occurs when the value of the IsMouseCaptured property changes on this element. (Inherited from UIElement.)
IsMouseCaptureWithinChanged
Occurs when the value of the IsMouseCaptureWithinProperty changes on this element. (Inherited fromUIElement.)
IsMouseDirectlyOverChanged
Occurs when the value of the IsMouseDirectlyOver property changes on this element. (Inherited fromUIElement.)
IsStylusCapturedChanged
Occurs when the value of the IsStylusCaptured property changes on this element. (Inherited from UIElement.)
IsStylusCaptureWithinChanged
Occurs when the value of the IsStylusCaptureWithin property changes on this element. (Inherited fromUIElement.)
IsStylusDirectlyOverChanged
Occurs when the value of the IsStylusDirectlyOver property changes on this element. (Inherited from UIElement.)
IsVisibleChanged Occurs when the value of the IsVisible property changes on this element. (Inherited from UIElement.)
KeyDown Occurs when a key is pressed while focus is on this element. (Inherited from UIElement.)
KeyUp Occurs when a key is released while focus is on this element. (Inherited from UIElement.)
LayoutUpdated Occurs when the layout of the various visual elements associated with the current Dispatcher changes. (Inherited from UIElement.)
Loaded Occurs when the element is laid out, rendered, and ready for interaction. (Inherited from FrameworkElement.)
LostFocus Occurs when this element loses logical focus. (Inherited from UIElement.)
LostKeyboardFocus Occurs when the keyboard is no longer focused on this element,. (Inherited from UIElement.)
LostMouseCapture Occurs when this element loses mouse capture. (Inherited from UIElement.)
LostStylusCapture Occurs when this element loses stylus capture. (Inherited from UIElement.)
LostTouchCapture Occurs when this element loses a touch capture. (Inherited from UIElement.)
ManipulationBoundaryFeedback
Occurs when the manipulation encounters a boundary. (Inherited from UIElement.)
ManipulationCompleted
Occurs when a manipulation and inertia on the UIElement object is complete. (Inherited from UIElement.)
ManipulationDelta Occurs when the input device changes position during a manipulation. (Inherited from UIElement.)
164
ManipulationInertiaStarting
Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins.(Inherited from UIElement.)
ManipulationStarted Occurs when an input device begins a manipulation on the UIElement object. (Inherited from UIElement.)
ManipulationStarting Occurs when the manipulation processor is first created. (Inherited from UIElement.)
MouseDown Occurs when any mouse button is pressed while the pointer is over this element. (Inherited from UIElement.)
MouseEnter Occurs when the mouse pointer enters the bounds of this element. (Inherited from UIElement.)
MouseLeave Occurs when the mouse pointer leaves the bounds of this element. (Inherited from UIElement.)
MouseLeftButtonDown Occurs when the left mouse button is pressed while the mouse pointer is over this element. (Inherited fromUIElement.)
MouseLeftButtonUp Occurs when the left mouse button is released while the mouse pointer is over this element. (Inherited fromUIElement.)
MouseMove Occurs when the mouse pointer moves while over this element. (Inherited from UIElement.)
MouseRightButtonDown
Occurs when the right mouse button is pressed while the mouse pointer is over this element. (Inherited fromUIElement.)
MouseRightButtonUp Occurs when the right mouse button is released while the mouse pointer is over this element. (Inherited fromUIElement.)
MouseUp Occurs when any mouse button is released over this element. (Inherited from UIElement.)
MouseWheel Occurs when the user rotates the mouse wheel while the mouse pointer is over this element. (Inherited fromUIElement.)
PreviewDragEnter Occurs when the input system reports an underlying drag event with this element as the drag target. (Inherited from UIElement.)
PreviewDragLeave Occurs when the input system reports an underlying drag event with this element as the drag origin. (Inherited from UIElement.)
PreviewDragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target.(Inherited from UIElement.)
PreviewDrop Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement.)
PreviewGiveFeedback Occurs when a drag-and-drop operation is started. (Inherited from UIElement.)
PreviewGotKeyboardFo Occurs when the keyboard is focused on this element. (Inherited from UIElement.)
165
cus
PreviewKeyDown Occurs when a key is pressed while focus is on this element. (Inherited from UIElement.)
PreviewKeyUp Occurs when a key is released while focus is on this element. (Inherited from UIElement.)
PreviewLostKeyboardFocus
Occurs when the keyboard is no longer focused on this element. (Inherited from UIElement.)
PreviewMouseDown Occurs when any mouse button is pressed while the pointer is over this element. (Inherited from UIElement.)
PreviewMouseLeftButtonDown
Occurs when the left mouse button is pressed while the mouse pointer is over this element. (Inherited fromUIElement.)
PreviewMouseLeftButtonUp
Occurs when the left mouse button is released while the mouse pointer is over this element. (Inherited fromUIElement.)
PreviewMouseMove Occurs when the mouse pointer moves while the mouse pointer is over this element. (Inherited from UIElement.)
PreviewMouseRightButtonDown
Occurs when the right mouse button is pressed while the mouse pointer is over this element. (Inherited fromUIElement.)
PreviewMouseRightButtonUp
Occurs when the right mouse button is released while the mouse pointer is over this element. (Inherited fromUIElement.)
PreviewMouseUp Occurs when any mouse button is released while the mouse pointer is over this element. (Inherited fromUIElement.)
PreviewMouseWheel Occurs when the user rotates the mouse wheel while the mouse pointer is over this element. (Inherited fromUIElement.)
PreviewQueryContinueDrag
Occurs when there is a change in the keyboard or mouse button state during a drag-and-drop operation.(Inherited from UIElement.)
PreviewStylusButtonDown
Occurs when the stylus button is pressed while the pointer is over this element. (Inherited from UIElement.)
PreviewStylusButtonUp Occurs when the stylus button is released while the pointer is over this element. (Inherited from UIElement.)
PreviewStylusDown Occurs when the stylus touches the digitizer while it is over this element. (Inherited from UIElement.)
PreviewStylusInAirMove
Occurs when the stylus moves over an element without actually touching the digitizer. (Inherited fromUIElement.)
PreviewStylusInRange Occurs when the stylus is close enough to the digitizer to be detected, while over this element. (Inherited fromUIElement.)
PreviewStylusMove Occurs when the stylus moves while over the element. The stylus must move while being
166
detected by the digitizer to raise this event, otherwise, PreviewStylusInAirMove is raised instead. (Inherited from UIElement.)
PreviewStylusOutOfRange
Occurs when the stylus is too far from the digitizer to be detected. (Inherited from UIElement.)
PreviewStylusSystemGesture
Occurs when a user performs one of several stylus gestures. (Inherited from UIElement.)
PreviewStylusUp Occurs when the user raises the stylus off the digitizer while the stylus is over this element. (Inherited fromUIElement.)
PreviewTextInput Occurs when this element gets text in a device-independent manner. (Inherited from UIElement.)
PreviewTouchDown Occurs when a finger touches the screen while the finger is over this element. (Inherited from UIElement.)
PreviewTouchMove Occurs when a finger moves on the screen while the finger is over this element. (Inherited from UIElement.)
PreviewTouchUp Occurs when a finger is raised off of the screen while the finger is over this element. (Inherited from UIElement.)
QueryContinueDrag Occurs when there is a change in the keyboard or mouse button state during a drag-and-drop operation.(Inherited from UIElement.)
QueryCursor Occurs when the cursor is requested to display. This event is raised on an element each time that the mouse pointer moves to a new location, which means the cursor object might need to be changed based on its new position. (Inherited from UIElement.)
RequestBringIntoView Occurs when BringIntoView is called on this element. (Inherited from FrameworkElement.)
SizeChanged Occurs when either the ActualHeight or the ActualWidth properties change value on this element. (Inherited from FrameworkElement.)
SourceUpdated Occurs when the source value changes for any existing property binding on this element. (Inherited fromFrameworkElement.)
StylusButtonDown Occurs when the stylus button is pressed while the pointer is over this element. (Inherited from UIElement.)
StylusButtonUp Occurs when the stylus button is released while the pointer is over this element. (Inherited from UIElement.)
StylusDown Occurs when the stylus touches the digitizer while the stylus is over this element. (Inherited from UIElement.)
StylusEnter Occurs when the stylus enters the bounds of this element. (Inherited from UIElement.)
StylusInAirMove Occurs when the stylus moves over an element without actually touching the digitizer. (Inherited fromUIElement.)
167
StylusInRange Occurs when the stylus is close enough to the digitizer to be detected, while over this element. (Inherited fromUIElement.)
StylusLeave Occurs when the stylus leaves the bounds of the element. (Inherited from UIElement.)
StylusMove Occurs when the stylus moves over this element. The stylus must move while on the digitizer to raise this event. Otherwise, StylusInAirMove is raised instead. (Inherited from UIElement.)
StylusOutOfRange Occurs when the stylus is too far from the digitizer to be detected, while over this element. (Inherited fromUIElement.)
StylusSystemGesture Occurs when a user performs one of several stylus gestures. (Inherited from UIElement.)
StylusUp Occurs when the user raises the stylus off the digitizer while it is over this element. (Inherited from UIElement.)
TargetUpdated Occurs when the target value changes for any property binding on this element. (Inherited fromFrameworkElement.)
TextInput Occurs when this element gets text in a device-independent manner. (Inherited from UIElement.)
ToolTipClosing Occurs just before any tooltip on the element is closed. (Inherited from FrameworkElement.)
ToolTipOpening Occurs when any tooltip on the element is opened. (Inherited from FrameworkElement.)
TouchDown Occurs when a finger touches the screen while the finger is over this element. (Inherited from UIElement.)
TouchEnter Occurs when a touch moves from outside to inside the bounds of this element. (Inherited from UIElement.)
TouchLeave Occurs when a touch moves from inside to outside the bounds of this element. (Inherited from UIElement.)
TouchMove Occurs when a finger moves on the screen while the finger is over this element. (Inherited from UIElement.)
TouchUp Occurs when a finger is raised off of the screen while the finger is over this element. (Inherited from UIElement.)
Unloaded Occurs when the element is removed from within an element tree of loaded elements. (Inherited fromFrameworkElement.)
Top
Fields
168
Name Description
DataProperty Identifies the Data dependency property.
Top
Explicit Interface Implementations
Name Description
IQueryAmbient.IsAmbientPropertyAvailable
For a description of this member, see the IsAmbientPropertyAvailable method. (Inherited fromFrameworkElement.)
Top
Remarks
The Path object can draw closed or open shapes, multiple shapes, and even curved shapes.
Unlike the Line and Polyline objects, you can use this object to draw curves. See the Data property for a description of
the shapes that the Path element supports.
Examples
The following example shows how to create a Path element and set its properties by using code.
C#
C++
VB
//Add the Path Element myPath = new Path(); myPath.Stroke = System.Windows.Media.Brushes.Black; myPath.Fill = System.Windows.Media.Brushes.MediumSlateBlue; myPath.StrokeThickness = 4; myPath.HorizontalAlignment = HorizontalAlignment.Left; myPath.VerticalAlignment = VerticalAlignment.Center; EllipseGeometry myEllipseGeometry = new EllipseGeometry(); myEllipseGeometry.Center = new System.Windows.Point(50,50); myEllipseGeometry.RadiusX = 25; myEllipseGeometry.RadiusY = 25; myPath.Data = myEllipseGeometry; myGrid.Children.Add(myPath);
169
More Code
How to: Create a LineSegment in a PathGeometry
This example shows how to create a line segment. To create a line segment, use the PathGeometry, PathFigure, and LineSegment classes.
How to: Create an Elliptical Arc
This example shows how to draw an elliptical arc. To create an elliptical arc, use the PathGeometry, PathFigure, and ArcSegment classes.
How to: Create a Cubic Bezier Curve
This example shows how to create a cubic Bezier curve. To create a cubic Bezier curve, use the PathGeometry, PathFigure, and BezierSegmentclasses. To display the resulting geometry, use a Path element, or use it with a GeometryDrawing or a DrawingContext. In the following examples, a cubic Bezier curve is drawn from (10, 100) to (300, 100). The curve has control points of (100, 0) and (200, 200).
How to: Create a Composite Shape
This example shows how to create composite shapes using Geometry objects and display them using a Path element. In the following example, a LineGeometry, EllipseGeometry, and a RectangleGeometry are used with a GeometryGroup to create a composite shape. The geometries are then drawn using a Path element.
How to: Create a Shape by Using a PathGeometry
This example shows how to create a shape using the PathGeometry class. PathGeometry objects are composed of one or more PathFigureobjects; each PathFigure represents a different "figure" or shape. Each PathFigure is itself composed of one or more PathSegment objects, each representing a connected portion of the figure or shape. Segment types include LineSegment, ArcSegment, and BezierSegment.
How to: Animate an EllipseGeometry
This example shows how to animate a Geometry within a Path element. In the following example, a PointAnimation is used to animate theCenter of an EllipseGeometry.
Version Information
.NET Framework
Supported in: 4, 3.5, 3.0
.NET Framework Client Profile
Supported in: 4, 3.5 SP1
Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows
Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET
Framework System Requirements.
Thread Safety
170
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not
guaranteed to be thread safe.
See Also
Reference
System.Windows.Shapes Namespace
Data
Other Resources
Shapes and Basic Drawing in WPF Overview
Shapes How-to Topics
171
StreamGeometry Class .NET Framework 4
Defines a geometric shape, described using a StreamGeometryContext. This geometry is light-weight alternative
to PathGeometry: it does not support data binding, animation, or modification.
Inheritance Hierarchy
System.Object
System.Windows.Threading.DispatcherObject
System.Windows.DependencyObject
System.Windows.Freezable
System.Windows.Media.Animation.Animatable
System.Windows.Media.Geometry
System.Windows.Media.StreamGeometry
Namespace: System.Windows.Media
Assembly: PresentationCore (in PresentationCore.dll)
XMLNS for XAML: http://schemas.microsoft.com/winfx/2006/xaml/presentation,
http://schemas.microsoft.com/netfx/2007/xaml/presentation
Syntax
C#
C++
F#
VB
[TypeConverterAttribute(typeof(GeometryConverter))] public sealed class StreamGeometry : Geometry
XAML Object Element Usage
<StreamGeometry .../>
XAML Attribute Usage
<object property="moveAndDrawCommands"/>
XAML Values
moveAndDrawCommands
One or more move and draw commands. See Path Markup Syntax.
The StreamGeometry type exposes the following members.
Constructors
Name Description
StreamGeometry Initializes a new, empty instance of the StreamGeometry class.
Properties
172
Name Description
Bounds Gets a Rect that is exactly large enough to contain
this StreamGeometry. (Overrides Geometry.Bounds.)
CanFreeze Gets a value that indicates whether the object can be made unmodifiable. (Inherited
from Freezable.)
DependencyObject
Type
Gets the DependencyObjectType that wraps the CLR type of this instance. (Inherited
from DependencyObject.)
Dispatcher Gets the Dispatcher this DispatcherObject is associated with. (Inherited
from DispatcherObject.)
FillRule Gets or sets a value that determines how the intersecting areas contained in
this StreamGeometry are combined.
HasAnimatedPrope
rties
Gets a value that indicates whether one or more AnimationClock objects is associated
with any of this object's dependency properties. (Inherited from Animatable.)
IsFrozen Gets a value that indicates whether the object is currently modifiable. (Inherited
from Freezable.)
IsSealed Gets a value that indicates whether this instance is currently sealed (read-
only). (Inherited from DependencyObject.)
Transform Gets or sets the Transform object applied to a Geometry. (Inherited from Geometry.)
Top
Methods
Name Description
ApplyAnimationClock(Dependen
cyProperty, AnimationClock)
Applies an AnimationClock to the specified DependencyProperty. If
the property is already animated, the SnapshotAndReplace handoff
behavior is used. (Inherited from Animatable.)
ApplyAnimationClock(Dependen
cyProperty, AnimationClock,
HandoffBehavior)
Applies an AnimationClock to the specified DependencyProperty. If
the property is already animated, the specified HandoffBehavior is
used. (Inherited from Animatable.)
BeginAnimation(DependencyPro
perty, AnimationTimeline)
Applies an animation to the specified DependencyProperty. The
animation is started when the next frame is rendered. If the specified
property is already animated, theSnapshotAndReplace handoff behavior
is used. (Inherited from Animatable.)
BeginAnimation(DependencyPro
perty, AnimationTimeline,
HandoffBehavior)
Applies an animation to the specified DependencyProperty. The
animation is started when the next frame is rendered. If the specified
property is already animated, the specifiedHandoffBehavior is
used. (Inherited from Animatable.)
CheckAccess Determines whether the calling thread has access to
173
this DispatcherObject. (Inherited fromDispatcherObject.)
Clear Removes all geometric information from this StreamGeometry.
ClearValue(DependencyProperty) Clears the local value of a property. The property to be cleared is
specified by aDependencyProperty identifier. (Inherited
from DependencyObject.)
ClearValue(DependencyProperty
Key)
Clears the local value of a read-only property. The property to be
cleared is specified by aDependencyPropertyKey. (Inherited
from DependencyObject.)
Clone Creates a modifiable clone of this StreamGeometry, making deep
copies of this object's values. When copying dependency properties,
this method copies resource references and data bindings (but they
might no longer resolve) but not animations or their current values.
CloneCore Makes the instance a clone (deep copy) of the specified Freezable using
base (non-animated) property values. (Inherited from Freezable.)
CloneCurrentValue Creates a modifiable clone of this StreamGeometry object, making
deep copies of this object's current values. Resource references, data
bindings, and animations are not copied, but their current values are.
CloneCurrentValueCore Makes the instance a modifiable clone (deep copy) of the
specified Freezable using current property values. (Inherited
from Freezable.)
CoerceValue Coerces the value of the specified dependency property. This is
accomplished by invoking any CoerceValueCallback function specified
in property metadata for the dependency property as it exists on the
calling DependencyObject. (Inherited from DependencyObject.)
CreateInstance Initializes a new instance of the Freezable class. (Inherited
from Freezable.)
CreateInstanceCore When implemented in a derived class, creates a new instance of
the Freezable derived class.(Inherited from Freezable.)
Equals Determines whether a provided DependencyObject is equivalent to the
currentDependencyObject. (Inherited from DependencyObject.)
FillContains(Geometry) Indicates whether the current geometry completely contains the
specified Geometry.(Inherited from Geometry.)
FillContains(Point) Indicates whether the geometry contains the specified Point. (Inherited
from Geometry.)
FillContains(Geometry, Double,
ToleranceType)
Indicates whether the current geometry contains the
specified Geometry, given the specified margin of error. (Inherited
from Geometry.)
174
FillContains(Point, Double,
ToleranceType)
Indicates whether the geometry contains the specified Point, given the
specified margin of error. (Inherited from Geometry.)
FillContainsWithDetail(Geometry
)
Returns a value that describes the intersection between the current
geometry and the specified geometry. (Inherited from Geometry.)
FillContainsWithDetail(Geometry
, Double, ToleranceType)
Returns a value that describes the intersection between the current
geometry and the specified geometry, given the specified margin of
error. (Inherited from Geometry.)
Finalize Allows an object to try to free resources and perform other cleanup
operations before it is reclaimed by garbage collection. (Inherited
from Object.)
Freeze() Makes the current object unmodifiable and sets its IsFrozen property
to true. (Inherited fromFreezable.)
FreezeCore Makes this Animatable object unmodifiable or determines whether it
can be made unmodifiable. (Inherited from Animatable.)
GetAnimationBaseValue Returns the non-animated value of the
specified DependencyProperty. (Inherited fromAnimatable.)
GetArea() Gets the area of the filled region of the Geometry object. (Inherited
from Geometry.)
GetArea(Double, ToleranceType) Gets the area, within the specified tolerance, of the filled region of
the Geometry object.(Inherited from Geometry.)
GetAsFrozen Creates a frozen copy of the Freezable, using base (non-animated)
property values. Because the copy is frozen, any frozen sub-objects are
copied by reference. (Inherited fromFreezable.)
GetAsFrozenCore Makes the instance a frozen clone of the specified Freezable using base
(non-animated) property values. (Inherited from Freezable.)
GetCurrentValueAsFrozen Creates a frozen copy of the Freezable using current property values.
Because the copy is frozen, any frozen sub-objects are copied by
reference. (Inherited from Freezable.)
GetCurrentValueAsFrozenCore Makes the current instance a frozen clone of the specified Freezable. If
the object has animated dependency properties, their current animated
values are copied. (Inherited fromFreezable.)
GetFlattenedPathGeometry() Gets a PathGeometry that is a polygonal approximation of
the Geometry object. (Inherited from Geometry.)
GetFlattenedPathGeometry(Doubl
e, ToleranceType)
Gets a PathGeometry, within the specified tolerance, that is a polygonal
approximation of theGeometry object. (Inherited from Geometry.)
GetHashCode Gets a hash code for this DependencyObject. (Inherited
from DependencyObject.)
175
GetLocalValueEnumerator Creates a specialized enumerator for determining which dependency
properties have locally set values on this DependencyObject. (Inherited
from DependencyObject.)
GetOutlinedPathGeometry() Gets a PathGeometry that is a simplified outline of the filled region of
the Geometry.(Inherited from Geometry.)
GetOutlinedPathGeometry(Doubl
e, ToleranceType)
Gets a PathGeometry, within the specified tolerance, that is a simplified
outline of the filled region of the Geometry. (Inherited from Geometry.)
GetRenderBounds(Pen) Returns an axis-aligned rectangle that is exactly large enough to contain
the geometry after it has been outlined with the
specified Pen. (Inherited from Geometry.)
GetRenderBounds(Pen, Double,
ToleranceType)
Returns an axis-aligned rectangle that is exactly large enough to contain
the geometry after it has been outlined with the specified Pen, given the
specified tolerance factor. (Inherited fromGeometry.)
GetType Gets the Type of the current instance. (Inherited from Object.)
GetValue Returns the current effective value of a dependency property on this
instance of aDependencyObject. (Inherited from DependencyObject.)
GetWidenedPathGeometry(Pen) Gets a PathGeometry that is the shape defined by the stroke on
the Geometry produced by the specified Pen. (Inherited
from Geometry.)
GetWidenedPathGeometry(Pen,
Double, ToleranceType)
Gets a PathGeometry that is the shape defined by the stroke on
the Geometry produced by the specified Pen, given the specified
tolerance factor. (Inherited from Geometry.)
InvalidateProperty Re-evaluates the effective value for the specified dependency
property (Inherited fromDependencyObject.)
IsEmpty Determines whether this StreamGeometry describes a geometric
shape. (OverridesGeometry.IsEmpty().)
MayHaveCurves Determines whether this StreamGeometry contains a curved
segment. (OverridesGeometry.MayHaveCurves().)
MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
OnChanged Called when the current Freezable object is modified. (Inherited
from Freezable.)
OnFreezablePropertyChanged(De
pendencyObject,
DependencyObject)
Ensures that appropriate context pointers are established for
a DependencyObjectType data member that has just been set. (Inherited
from Freezable.)
OnFreezablePropertyChanged(De
pendencyObject,
DependencyObject,
This member supports the Windows Presentation Foundation (WPF)
infrastructure and is not intended to be used directly from your
code. (Inherited from Freezable.)
176
DependencyProperty)
OnPropertyChanged Overrides the DependencyObject implementation
of OnPropertyChanged to also invoke anyChanged handlers in response
to a changing dependency property of type Freezable.(Inherited
from Freezable.)
Open Opens a StreamGeometryContext that can be used to describe
this StreamGeometry object's contents.
ReadLocalValue Returns the local value of a dependency property, if it exists. (Inherited
fromDependencyObject.)
ReadPreamble Ensures that the Freezable is being accessed from a valid thread.
Inheritors of Freezable must call this method at the beginning of any
API that reads data members that are not dependency
properties. (Inherited from Freezable.)
SetCurrentValue Sets the value of a dependency property without changing its value
source. (Inherited fromDependencyObject.)
SetValue(DependencyProperty,
Object)
Sets the local value of a dependency property, specified by its
dependency property identifier. (Inherited from DependencyObject.)
SetValue(DependencyPropertyKe
y, Object)
Sets the local value of a read-only dependency property, specified by
theDependencyPropertyKey identifier of the dependency
property. (Inherited fromDependencyObject.)
ShouldSerializeProperty Returns a value that indicates whether serialization processes should
serialize the value for the provided dependency property. (Inherited
from DependencyObject.)
ShouldSerializeTransform Gets a value that indicates whether the value of the Transform property
should be serialized.(Inherited from Geometry.)
StrokeContains(Pen, Point) Determines whether the specified Point is contained in the stroke
produced by applying the specified Pen to the geometry. (Inherited
from Geometry.)
StrokeContains(Pen, Point,
Double, ToleranceType)
Determines whether the specified Point is contained in the stroke
produced by applying the specified Pen to the geometry, given the
specified margin of error. (Inherited fromGeometry.)
StrokeContainsWithDetail(Pen,
Geometry)
Returns a value that describes the intersection between the
specified Geometry and the stroke created by applying the
specified Pen to the current geometry. (Inherited fromGeometry.)
StrokeContainsWithDetail(Pen,
Geometry, Double,
ToleranceType)
Gets a value that describes the intersection between the
specified Geometry and the stroke created by applying the
specified Pen to the current geometry, given the specified margin of
error. (Inherited from Geometry.)
177
ToString() Creates a string representation of the object based on the current
culture. (Inherited fromGeometry.)
ToString(IFormatProvider) Creates a string representation of the object using the specified culture-
specific formatting information. (Inherited from Geometry.)
VerifyAccess Enforces that the calling thread has access to
this DispatcherObject. (Inherited fromDispatcherObject.)
WritePostscript Raises the Changed event for the Freezable and invokes
its OnChanged method. Classes that derive from Freezable should call
this method at the end of any API that modifies class members that are
not stored as dependency properties. (Inherited from Freezable.)
WritePreamble Verifies that the Freezable is not frozen and that it is being accessed
from a valid threading context. Freezable inheritors should call this
method at the beginning of any API that writes to data members that are
not dependency properties. (Inherited from Freezable.)
Top
Events
Name Description
Changed Occurs when the Freezable or an object it contains is modified. (Inherited
from Freezable.)
Top
Fields
Name Description
FillRuleProperty Identifies the FillRule dependency property.
Top
Explicit Interface Implementations
Name Description
IFormattable.ToS
tring
Formats the value of the current instance using the specified format. (Inherited
from Geometry.)
Top
Remarks
Use a StreamGeometry when you need to describe a complex geometry but do not want the overhead of supporting
data binding, animation, or modification. Because of its efficiency, the StreamGeometry class is a good choice for
describing adorners.
A StreamGeometry cannot be serialized if it contains a Transform or any non-stroked or unfilled segments.
178
Freezable Features
A StreamGeometry is a Freezable type. For information about Freezable features, such as freezing and cloning, see
the Freezable Objects Overview.
Examples
StreamGeometry is light-weight alternative to PathGeometry for creating geometric shapes. Use
a StreamGeometry when you need to describe a complex geometry but do not want the overhead of supporting data
binding, animation, or modification. For example, because of its efficiency, the StreamGeometryclass is a good choice
for describing adorners.
The following example uses attribute syntax to create a triangular StreamGeometry in XAML.
XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel> <Path Data="F0 M10,100 L100,100 100,50Z" StrokeThickness="1" Stroke="Black"/> </StackPanel> </Page>
For more information about StreamGeometry attribute syntax, see the Path Markup Syntax page.
The next example uses a StreamGeometry to define a triangle in code. First, the example creates a StreamGeometry,
then obtains a StreamGeometryContextand uses it to describe the triangle.
C#
VB
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; namespace SDKSample { // Use StreamGeometry with StreamGeometryContext to define a triangle shape. public partial class StreamGeometryTriangleExample : Page { public StreamGeometryTriangleExample() { // Create a path to draw a geometry with. Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; // Create a StreamGeometry to use to specify myPath. StreamGeometry geometry = new StreamGeometry(); geometry.FillRule = FillRule.EvenOdd; // Open a StreamGeometryContext that can be used to describe this StreamGeometry // object's contents. using (StreamGeometryContext ctx = geometry.Open())
179
{ // Begin the triangle at the point specified. Notice that the shape is set to // be closed so only two lines need to be specified below to make the triangle. ctx.BeginFigure(new Point(10, 100), true /* is filled */, true /* is closed */); // Draw a line to the next specified point. ctx.LineTo(new Point(100, 100), true /* is stroked */, false /* is smooth join */); // Draw another line to the next specified point. ctx.LineTo(new Point(100, 50), true /* is stroked */, false /* is smooth join */); } // Freeze the geometry (make it unmodifiable) // for additional performance benefits. geometry.Freeze(); // Specify the shape (triangle) of the Path using the StreamGeometry. myPath.Data = geometry; // Add path shape to the UI. StackPanel mainPanel = new StackPanel(); mainPanel.Children.Add(myPath); this.Content = mainPanel; } } }
The next example creates a method that uses a StreamGeometry and StreamGeometryContext to define a geometric
shape based on specified parameters.
C#
VB using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; namespace SDKSample { public partial class StreamGeometryExample : Page { public StreamGeometryExample() { // Create a path to draw a geometry with. Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; // Create a StreamGeometry to use to specify myPath. StreamGeometry theGeometry = BuildRegularPolygon(new Point(200, 200), 200, 8, 0); theGeometry.FillRule = FillRule.EvenOdd; // Freeze the geometry (make it unmodifiable) // for additional performance benefits. theGeometry.Freeze(); // Use the StreamGeometry returned by the BuildRegularPolygon to // specify the shape of the path. myPath.Data = theGeometry;
180
// Add path shape to the UI. StackPanel mainPanel = new StackPanel(); mainPanel.Children.Add(myPath); this.Content = mainPanel; } StreamGeometry BuildRegularPolygon(Point c, double r, int numSides, double offsetDegree) { // c is the center, r is the radius, // numSides the number of sides, offsetDegree the offset in Degrees. // Do not add the last point. StreamGeometry geometry = new StreamGeometry(); using (StreamGeometryContext ctx = geometry.Open()) { ctx.BeginFigure(new Point(), true /* is filled */, true /* is closed */); double step = 2 * Math.PI / Math.Max(numSides, 3); Point cur = c; double a = Math.PI * offsetDegree / 180.0; for (int i = 0; i < numSides; i++, a += step) { cur.X = c.X + r * Math.Cos(a); cur.Y = c.Y + r * Math.Sin(a); ctx.LineTo(cur, true /* is stroked */, false /* is smooth join */); } } return geometry; } } }
Version Information
.NET Framework
Supported in: 4, 3.5, 3.0
.NET Framework Client Profile
Supported in: 4, 3.5 SP1
Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows
Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET
Framework System Requirements.
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not
guaranteed to be thread safe.
181
See Also
Reference
System.Windows.Media Namespace
Other Resources
Path Markup Syntax
Geometry Overview
Adorners Overview
182
PathGeometry Class .NET Framework 4
Represents a complex shape that may be composed of arcs, curves, ellipses, lines, and rectangles.
Inheritance Hierarchy
System.Object
System.Windows.Threading.DispatcherObject
System.Windows.DependencyObject
System.Windows.Freezable
System.Windows.Media.Animation.Animatable
System.Windows.Media.Geometry
System.Windows.Media.PathGeometry
Namespace: System.Windows.Media
Assembly: PresentationCore (in PresentationCore.dll)
XMLNS for XAML: http://schemas.microsoft.com/winfx/2006/xaml/presentation,
http://schemas.microsoft.com/netfx/2007/xaml/presentation
Syntax
C#
C++
F#
VB
[ContentPropertyAttribute("Figures")] public sealed class PathGeometry : Geometry
XAML Object Element Usage
<PathGeometry> Figures </PathGeometry>
The PathGeometry type exposes the following members.
Constructors
Name Description
PathGeometry() Initializes a new instance of the PathGeometry class.
PathGeometry(IEnumerable<PathFigure>) Initializes a new instance of the PathGeometry class with the
specified Figures.
PathGeometry(IEnumerable<PathFigure>,
FillRule, Transform)
Initializes a new instance of the PathGeometry class with the
specified Figures, FillRule, and Transform.
Top
Properties
Name Description
183
Bounds Gets a Rect that specifies the bounding box of
this PathGeometry object. Note: This method does not take any pens into
account. (Overrides Geometry.Bounds.)
CanFreeze Gets a value that indicates whether the object can be made
unmodifiable. (Inherited from Freezable.)
DependencyObjectType Gets the DependencyObjectType that wraps the CLR type of this
instance. (Inherited from DependencyObject.)
Dispatcher Gets the Dispatcher this DispatcherObject is associated with. (Inherited
from DispatcherObject.)
Figures Gets or sets the collection of PathFigure objects that describe the path's contents.
FillRule Gets or sets a value that determines how the intersecting areas contained in
this PathGeometry are combined.
HasAnimatedProperties Gets a value that indicates whether one or more AnimationClock objects is
associated with any of this object's dependency properties. (Inherited
from Animatable.)
IsFrozen Gets a value that indicates whether the object is currently modifiable. (Inherited
from Freezable.)
IsSealed Gets a value that indicates whether this instance is currently sealed (read-
only). (Inherited from DependencyObject.)
Transform Gets or sets the Transform object applied to a Geometry. (Inherited
from Geometry.)
Top
Methods
Name Description
AddGeometry Converts the specified Geometry into a collection of PathFigure objects
and adds it to the path. Note: If the specified Geometry is animated, the
conversion from Geometry toPathFigure may result in some loss of
information.
ApplyAnimationClock(Depende
ncyProperty, AnimationClock)
Applies an AnimationClock to the specified DependencyProperty. If the
property is already animated, the SnapshotAndReplace handoff behavior
is used. (Inherited from Animatable.)
ApplyAnimationClock(Depende
ncyProperty, AnimationClock,
HandoffBehavior)
Applies an AnimationClock to the specified DependencyProperty. If the
property is already animated, the specified HandoffBehavior is
used. (Inherited from Animatable.)
BeginAnimation(DependencyPr
operty, AnimationTimeline)
Applies an animation to the specified DependencyProperty. The
animation is started when the next frame is rendered. If the specified
184
property is already animated, theSnapshotAndReplace handoff behavior
is used. (Inherited from Animatable.)
BeginAnimation(DependencyPr
operty, AnimationTimeline,
HandoffBehavior)
Applies an animation to the specified DependencyProperty. The
animation is started when the next frame is rendered. If the specified
property is already animated, the specifiedHandoffBehavior is
used. (Inherited from Animatable.)
CheckAccess Determines whether the calling thread has access to
this DispatcherObject. (Inherited fromDispatcherObject.)
Clear Removes all PathFigure objects from this PathGeometry.
ClearValue(DependencyPropert
y)
Clears the local value of a property. The property to be cleared is
specified by aDependencyProperty identifier. (Inherited
from DependencyObject.)
ClearValue(DependencyPropert
yKey)
Clears the local value of a read-only property. The property to be cleared
is specified by aDependencyPropertyKey. (Inherited
from DependencyObject.)
Clone Creates a modifiable clone of this PathGeometry, making deep copies
of this object's values. When copying dependency properties, this method
copies resource references and data bindings (but they might no longer
resolve) but not animations or their current values.
CloneCore Makes the instance a clone (deep copy) of the specified Freezable using
base (non-animated) property values. (Inherited from Freezable.)
CloneCurrentValue Creates a modifiable clone of this PathGeometry object, making deep
copies of this object's current values. Resource references, data bindings,
and animations are not copied, but their current values are.
CloneCurrentValueCore Makes the instance a modifiable clone (deep copy) of the
specified Freezable using current property values. (Inherited
from Freezable.)
CoerceValue Coerces the value of the specified dependency property. This is
accomplished by invoking any CoerceValueCallback function specified
in property metadata for the dependency property as it exists on the
calling DependencyObject. (Inherited from DependencyObject.)
CreateFromGeometry Creates a PathGeometry version of the specified Geometry.
CreateInstance Initializes a new instance of the Freezable class. (Inherited
from Freezable.)
CreateInstanceCore When implemented in a derived class, creates a new instance of
the Freezable derived class.(Inherited from Freezable.)
Equals Determines whether a provided DependencyObject is equivalent to the
currentDependencyObject. (Inherited from DependencyObject.)
185
FillContains(Geometry) Indicates whether the current geometry completely contains the
specified Geometry.(Inherited from Geometry.)
FillContains(Point) Indicates whether the geometry contains the specified Point. (Inherited
from Geometry.)
FillContains(Geometry, Double,
ToleranceType)
Indicates whether the current geometry contains the specified Geometry,
given the specified margin of error. (Inherited from Geometry.)
FillContains(Point, Double,
ToleranceType)
Indicates whether the geometry contains the specified Point, given the
specified margin of error. (Inherited from Geometry.)
FillContainsWithDetail(Geomet
ry)
Returns a value that describes the intersection between the current
geometry and the specified geometry. (Inherited from Geometry.)
FillContainsWithDetail(Geomet
ry, Double, ToleranceType)
Returns a value that describes the intersection between the current
geometry and the specified geometry, given the specified margin of
error. (Inherited from Geometry.)
Finalize Allows an object to try to free resources and perform other cleanup
operations before it is reclaimed by garbage collection. (Inherited
from Object.)
Freeze() Makes the current object unmodifiable and sets its IsFrozen property
to true. (Inherited fromFreezable.)
FreezeCore Makes this Animatable object unmodifiable or determines whether it can
be made unmodifiable. (Inherited from Animatable.)
GetAnimationBaseValue Returns the non-animated value of the
specified DependencyProperty. (Inherited fromAnimatable.)
GetArea() Gets the area of the filled region of the Geometry object. (Inherited
from Geometry.)
GetArea(Double,
ToleranceType)
Gets the area, within the specified tolerance, of the filled region of
the Geometry object.(Inherited from Geometry.)
GetAsFrozen Creates a frozen copy of the Freezable, using base (non-animated)
property values. Because the copy is frozen, any frozen sub-objects are
copied by reference. (Inherited fromFreezable.)
GetAsFrozenCore Makes the instance a frozen clone of the specified Freezable using base
(non-animated) property values. (Inherited from Freezable.)
GetCurrentValueAsFrozen Creates a frozen copy of the Freezable using current property values.
Because the copy is frozen, any frozen sub-objects are copied by
reference. (Inherited from Freezable.)
GetCurrentValueAsFrozenCore Makes the current instance a frozen clone of the specified Freezable. If
the object has animated dependency properties, their current animated
values are copied. (Inherited fromFreezable.)
186
GetFlattenedPathGeometry() Gets a PathGeometry that is a polygonal approximation of
the Geometry object. (Inherited from Geometry.)
GetFlattenedPathGeometry(Dou
ble, ToleranceType)
Gets a PathGeometry, within the specified tolerance, that is a polygonal
approximation of theGeometry object. (Inherited from Geometry.)
GetHashCode Gets a hash code for this DependencyObject. (Inherited
from DependencyObject.)
GetLocalValueEnumerator Creates a specialized enumerator for determining which dependency
properties have locally set values on this DependencyObject. (Inherited
from DependencyObject.)
GetOutlinedPathGeometry() Gets a PathGeometry that is a simplified outline of the filled region of
the Geometry.(Inherited from Geometry.)
GetOutlinedPathGeometry(Dou
ble, ToleranceType)
Gets a PathGeometry, within the specified tolerance, that is a simplified
outline of the filled region of the Geometry. (Inherited from Geometry.)
GetPointAtFractionLength Gets the Point and a tangent vector on this PathGeometry at the
specified fraction of its length.
GetRenderBounds(Pen) Returns an axis-aligned rectangle that is exactly large enough to contain
the geometry after it has been outlined with the specified Pen. (Inherited
from Geometry.)
GetRenderBounds(Pen, Double,
ToleranceType)
Returns an axis-aligned rectangle that is exactly large enough to contain
the geometry after it has been outlined with the specified Pen, given the
specified tolerance factor. (Inherited fromGeometry.)
GetType Gets the Type of the current instance. (Inherited from Object.)
GetValue Returns the current effective value of a dependency property on this
instance of aDependencyObject. (Inherited from DependencyObject.)
GetWidenedPathGeometry(Pen) Gets a PathGeometry that is the shape defined by the stroke on
the Geometry produced by the specified Pen. (Inherited from Geometry.)
GetWidenedPathGeometry(Pen,
Double, ToleranceType)
Gets a PathGeometry that is the shape defined by the stroke on
the Geometry produced by the specified Pen, given the specified
tolerance factor. (Inherited from Geometry.)
InvalidateProperty Re-evaluates the effective value for the specified dependency
property (Inherited fromDependencyObject.)
IsEmpty Determines whether this PathGeometry object is
empty. (Overrides Geometry.IsEmpty().)
MayHaveCurves Determines whether this PathGeometry object may have curved
segments. (OverridesGeometry.MayHaveCurves().)
MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
187
OnChanged Called when the current Freezable object is modified. (Inherited
from Freezable.)
OnFreezablePropertyChanged(D
ependencyObject,
DependencyObject)
Ensures that appropriate context pointers are established for
a DependencyObjectType data member that has just been set. (Inherited
from Freezable.)
OnFreezablePropertyChanged(D
ependencyObject,
DependencyObject,
DependencyProperty)
This member supports the Windows Presentation Foundation (WPF)
infrastructure and is not intended to be used directly from your
code. (Inherited from Freezable.)
OnPropertyChanged Overrides the DependencyObject implementation
of OnPropertyChanged to also invoke anyChanged handlers in response
to a changing dependency property of type Freezable.(Inherited
from Freezable.)
ReadLocalValue Returns the local value of a dependency property, if it exists. (Inherited
fromDependencyObject.)
ReadPreamble Ensures that the Freezable is being accessed from a valid thread.
Inheritors of Freezable must call this method at the beginning of any API
that reads data members that are not dependency properties. (Inherited
from Freezable.)
SetCurrentValue Sets the value of a dependency property without changing its value
source. (Inherited fromDependencyObject.)
SetValue(DependencyProperty,
Object)
Sets the local value of a dependency property, specified by its
dependency property identifier. (Inherited from DependencyObject.)
SetValue(DependencyPropertyK
ey, Object)
Sets the local value of a read-only dependency property, specified by
theDependencyPropertyKey identifier of the dependency
property. (Inherited fromDependencyObject.)
ShouldSerializeProperty Returns a value that indicates whether serialization processes should
serialize the value for the provided dependency property. (Inherited
from DependencyObject.)
ShouldSerializeTransform Gets a value that indicates whether the value of the Transform property
should be serialized.(Inherited from Geometry.)
StrokeContains(Pen, Point) Determines whether the specified Point is contained in the stroke
produced by applying the specified Pen to the geometry. (Inherited
from Geometry.)
StrokeContains(Pen, Point,
Double, ToleranceType)
Determines whether the specified Point is contained in the stroke
produced by applying the specified Pen to the geometry, given the
specified margin of error. (Inherited fromGeometry.)
StrokeContainsWithDetail(Pen,
Geometry)
Returns a value that describes the intersection between the
specified Geometry and the stroke created by applying the
188
specified Pen to the current geometry. (Inherited fromGeometry.)
StrokeContainsWithDetail(Pen,
Geometry, Double,
ToleranceType)
Gets a value that describes the intersection between the
specified Geometry and the stroke created by applying the
specified Pen to the current geometry, given the specified margin of
error. (Inherited from Geometry.)
ToString() Creates a string representation of the object based on the current
culture. (Inherited fromGeometry.)
ToString(IFormatProvider) Creates a string representation of the object using the specified culture-
specific formatting information. (Inherited from Geometry.)
VerifyAccess Enforces that the calling thread has access to
this DispatcherObject. (Inherited fromDispatcherObject.)
WritePostscript Raises the Changed event for the Freezable and invokes
its OnChanged method. Classes that derive from Freezable should call
this method at the end of any API that modifies class members that are
not stored as dependency properties. (Inherited from Freezable.)
WritePreamble Verifies that the Freezable is not frozen and that it is being accessed from
a valid threading context. Freezable inheritors should call this method at
the beginning of any API that writes to data members that are not
dependency properties. (Inherited from Freezable.)
Top
Events
Name Description
Changed Occurs when the Freezable or an object it contains is modified. (Inherited
from Freezable.)
Top
Fields
Name Description
FiguresProperty Identifies the Figures dependency property.
FillRuleProperty Identifies the FillRule dependency property.
Top
Explicit Interface Implementations
Name Description
IFormattable.ToString Formats the value of the current instance using the specified format. (Inherited
from Geometry.)
189
Top
Remarks
Each PathGeometry object defines a collection of PathFigure objects. Each of the PathFigure objects is composed of
one or more PathSegment objects, such asArcSegment and LineSegment, which actually define their shape.
The filled area of the PathGeometry is defined by taking all of the contained PathFigure objects that have
their IsFilled property set to true and applying theFillRule to determine the enclosed area.
Examples
This example shows how to create a line segment. To create a line segment, use the PathGeometry, PathFigure,
and LineSegment classes.
The following examples draw a LineSegment from (10, 50) to (200, 70). The following illustration shows the
resulting LineSegment; a grid background was added to show the coordinate system.
A LineSegment drawn from (10,50) to (200,700)
[xaml]
In Extensible Application Markup Language (XAML), you may use attribute syntax to describe a path.
XAML
<Path Stroke="Black" StrokeThickness="1" Data="M 10,50 L 200,70" />
[xaml]
(Note that this attribute syntax actually creates a StreamGeometry, a lighter-weight version of a PathGeometry. For
more information, see the Path Markup Syntax page.)
In XAML, you may also draw a line segment by using object element syntax. The following is equivalent to the previous
XAML example.
C#
VB
PathFigure myPathFigure = new PathFigure(); myPathFigure.StartPoint = new Point(10, 50); LineSegment myLineSegment = new LineSegment(); myLineSegment.Point = new Point(200, 70); PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection(); myPathSegmentCollection.Add(myLineSegment);
190
myPathFigure.Segments = myPathSegmentCollection; PathFigureCollection myPathFigureCollection = new PathFigureCollection(); myPathFigureCollection.Add(myPathFigure); PathGeometry myPathGeometry = new PathGeometry(); myPathGeometry.Figures = myPathFigureCollection; Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; myPath.Data = myPathGeometry;
XAML <Path Stroke="Black" StrokeThickness="1"> <Path.Data> <PathGeometry> <PathFigure StartPoint="10,50"> <LineSegment Point="200,70" /> </PathFigure> </PathGeometry> </Path.Data> </Path>
This example is part of larger sample; for the complete sample, see the Geometries Sample.
More Code
How to: Create an
Elliptical Arc
This example shows how to draw an elliptical arc. To create an elliptical arc, use
the PathGeometry, PathFigure, and ArcSegment classes.
How to: Create a
Cubic Bezier Curve
This example shows how to create a cubic Bezier curve. To create a cubic Bezier
curve, use the PathGeometry, PathFigure, andBezierSegment classes. To display
the resulting geometry, use a Path element, or use it with a GeometryDrawing or
a DrawingContext. In the following examples, a cubic Bezier curve is drawn from
(10, 100) to (300, 100). The curve has control points of (100, 0) and (200, 200).
How to: Create a
Quadratic Bezier
Curve
This example shows how to create a quadratic Bezier curve. To create a quadratic
Bezier curve, use the PathGeometry, PathFigure,
andQuadraticBezierSegment classes.
How to: Create a
Composite Shape
This example shows how to create composite shapes using Geometry objects and
display them using a Path element. In the following example,
a LineGeometry, EllipseGeometry, and a RectangleGeometry are used with
a GeometryGroup to create a composite shape. The geometries are then drawn
using a Path element.
How to: Create
Multiple Subpaths
Within a
PathGeometry
This example shows how to create multiple subpaths in a PathGeometry. To create
multiple subpaths, you create a PathFigure for each subpath.
How to: Control the The FillRule property of a GeometryGroup or a PathGeometry, specifies a "rule"
191
Fill of a Composite
Shape
which the composite shape uses to determine whether a given point is part of the
geometry. There are two possible values for FillRule: EvenOdd and Nonzero. The
following sections will describe how to use these two rules.
Version Information
.NET Framework
Supported in: 4, 3.5, 3.0
.NET Framework Client Profile
Supported in: 4, 3.5 SP1
Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows
Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET
Framework System Requirements.
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not
guaranteed to be thread safe.
See Also
Reference
System.Windows.Media Namespace
Other Resources
Geometry Overview
192
PathFigureCollection Class .NET Framework 4
Other Versions
This topic has not yet been rated Rate this topic
Represents a collection of PathFigure objects that collectively make up the geometry of a PathGeometry.
Inheritance Hierarchy
System.Object
System.Windows.Threading.DispatcherObject
System.Windows.DependencyObject
System.Windows.Freezable
System.Windows.Media.Animation.Animatable
System.Windows.Media.PathFigureCollection
Namespace: System.Windows.Media
Assembly: PresentationCore (in PresentationCore.dll)
XMLNS for XAML: http://schemas.microsoft.com/winfx/2006/xaml/presentation,
http://schemas.microsoft.com/netfx/2007/xaml/presentation
Syntax
C#
C++
F#
VB
[TypeConverterAttribute(typeof(PathFigureCollectionConverter))] public sealed class PathFigureCollection : Animatable, IFormattable, IList, ICollection, IList<PathFigure>, ICollection<PathFigure>, IEnumerable<PathFigure>, IEnumerable
XAML Object Element Usage
<PathFigureCollection .../>
XAML Implicit Collection Usage
<object> <object.property> oneOrMorePathFigureObjectElements </object.property> </object>
XAML Attribute Usage
<object property="drawingCommands" … />
XAML Values
drawingCommands
A space-delimited list of drawing commands, starting with a move-to command. For more information, see
the Path Markup Syntax overview.
oneOrMorePathFigureObjectElements
193
One or more PathFigure objects, declared using object element syntax.
The PathFigureCollection type exposes the following members.
Constructors
Name Description
PathFigureCollection() Initializes a new instance of the PathFigureCollection class.
PathFigureCollection(IE
numerable<PathFigure>)
Initializes a new instance of the PathFigureCollection class that contains the
specifiedPathFigure objects.
PathFigureCollection(Int
32)
Initializes a new instance of the PathFigureCollection class that can initially
contain the specified number of PathFigure objects.
Top
Properties
Name Description
CanFreeze Gets a value that indicates whether the object can be made
unmodifiable. (Inherited from Freezable.)
Count Gets the number of path figures contained in the PathFigureCollection.
DependencyObjectType Gets the DependencyObjectType that wraps the CLR type of this
instance. (Inherited from DependencyObject.)
Dispatcher Gets the Dispatcher this DispatcherObject is associated with. (Inherited
from DispatcherObject.)
HasAnimatedProperties Gets a value that indicates whether one or more AnimationClock objects is
associated with any of this object's dependency properties. (Inherited
from Animatable.)
IsFrozen Gets a value that indicates whether the object is currently modifiable. (Inherited
from Freezable.)
IsSealed Gets a value that indicates whether this instance is currently sealed (read-
only). (Inherited from DependencyObject.)
Item Gets or sets the PathFigure at the specified index position.
Top
Methods
Name Description
Add Adds a PathFigure to the end of the collection.
194
ApplyAnimationClock(Depe
ndencyProperty,
AnimationClock)
Applies an AnimationClock to the specified DependencyProperty. If the
property is already animated, the SnapshotAndReplace handoff behavior is
used. (Inherited from Animatable.)
ApplyAnimationClock(Depe
ndencyProperty,
AnimationClock,
HandoffBehavior)
Applies an AnimationClock to the specified DependencyProperty. If the
property is already animated, the specified HandoffBehavior is
used. (Inherited from Animatable.)
BeginAnimation(Dependency
Property,
AnimationTimeline)
Applies an animation to the specified DependencyProperty. The animation
is started when the next frame is rendered. If the specified property is
already animated, theSnapshotAndReplace handoff behavior is
used. (Inherited from Animatable.)
BeginAnimation(Dependency
Property,
AnimationTimeline,
HandoffBehavior)
Applies an animation to the specified DependencyProperty. The animation
is started when the next frame is rendered. If the specified property is
already animated, the specifiedHandoffBehavior is used. (Inherited
from Animatable.)
CheckAccess Determines whether the calling thread has access to
this DispatcherObject. (Inherited fromDispatcherObject.)
Clear Removes all items from the PathFigureCollection.
ClearValue(DependencyProp
erty)
Clears the local value of a property. The property to be cleared is specified
by aDependencyProperty identifier. (Inherited from DependencyObject.)
ClearValue(DependencyProp
ertyKey)
Clears the local value of a read-only property. The property to be cleared is
specified by aDependencyPropertyKey. (Inherited
from DependencyObject.)
Clone Creates a modifiable clone of this PathFigureCollection, making deep
copies of this object's values. When copying dependency properties, this
method copies resource references and data bindings (but they might no
longer resolve) but not animations or their current values.
CloneCore Makes the instance a clone (deep copy) of the specified Freezable using
base (non-animated) property values. (Inherited from Freezable.)
CloneCurrentValue Creates a modifiable clone of this PathFigureCollection object, making
deep copies of this object's current values. Resource references, data
bindings, and animations are not copied, but their current values are.
CloneCurrentValueCore Makes the instance a modifiable clone (deep copy) of the
specified Freezable using current property values. (Inherited
from Freezable.)
CoerceValue Coerces the value of the specified dependency property. This is
accomplished by invoking any CoerceValueCallback function specified in
property metadata for the dependency property as it exists on the
calling DependencyObject. (Inherited from DependencyObject.)
195
Contains Determines whether the collection contains the specified PathFigure.
CopyTo Copies the entire PathFigureCollection to a one-dimensional array of
type PathFigure, starting at the specified index of the target array.
CreateInstance Initializes a new instance of the Freezable class. (Inherited from Freezable.)
CreateInstanceCore When implemented in a derived class, creates a new instance of
the Freezable derived class.(Inherited from Freezable.)
Equals Determines whether a provided DependencyObject is equivalent to the
currentDependencyObject. (Inherited from DependencyObject.)
Finalize Allows an object to try to free resources and perform other cleanup
operations before it is reclaimed by garbage collection. (Inherited
from Object.)
Freeze() Makes the current object unmodifiable and sets its IsFrozen property
to true. (Inherited fromFreezable.)
FreezeCore Makes this Animatable object unmodifiable or determines whether it can be
made unmodifiable. (Inherited from Animatable.)
GetAnimationBaseValue Returns the non-animated value of the
specified DependencyProperty. (Inherited fromAnimatable.)
GetAsFrozen Creates a frozen copy of the Freezable, using base (non-animated) property
values. Because the copy is frozen, any frozen sub-objects are copied by
reference. (Inherited fromFreezable.)
GetAsFrozenCore Makes the instance a frozen clone of the specified Freezable using base
(non-animated) property values. (Inherited from Freezable.)
GetCurrentValueAsFrozen Creates a frozen copy of the Freezable using current property values.
Because the copy is frozen, any frozen sub-objects are copied by
reference. (Inherited from Freezable.)
GetCurrentValueAsFrozenCo
re
Makes the current instance a frozen clone of the specified Freezable. If the
object has animated dependency properties, their current animated values
are copied. (Inherited fromFreezable.)
GetEnumerator Returns an enumerator that can iterate through the collection.
GetHashCode Gets a hash code for this DependencyObject. (Inherited
from DependencyObject.)
GetLocalValueEnumerator Creates a specialized enumerator for determining which dependency
properties have locally set values on this DependencyObject. (Inherited
from DependencyObject.)
GetType Gets the Type of the current instance. (Inherited from Object.)
196
GetValue Returns the current effective value of a dependency property on this
instance of aDependencyObject. (Inherited from DependencyObject.)
IndexOf Searches for the specified PathFigure and returns the zero-based index of
the first occurrence within the entire collection.
Insert Inserts a PathFigure into a specific location within the collection.
InvalidateProperty Re-evaluates the effective value for the specified dependency
property (Inherited fromDependencyObject.)
MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
OnChanged Called when the current Freezable object is modified. (Inherited
from Freezable.)
OnFreezablePropertyChange
d(DependencyObject,
DependencyObject)
Ensures that appropriate context pointers are established for
a DependencyObjectType data member that has just been set. (Inherited
from Freezable.)
OnFreezablePropertyChange
d(DependencyObject,
DependencyObject,
DependencyProperty)
This member supports the Windows Presentation Foundation (WPF)
infrastructure and is not intended to be used directly from your
code. (Inherited from Freezable.)
OnPropertyChanged Overrides the DependencyObject implementation of OnPropertyChanged to
also invoke anyChanged handlers in response to a changing dependency
property of type Freezable.(Inherited from Freezable.)
Parse Returns an instance of PathFigureCollection created from a specified
string.
ReadLocalValue Returns the local value of a dependency property, if it exists. (Inherited
fromDependencyObject.)
ReadPreamble Ensures that the Freezable is being accessed from a valid thread. Inheritors
of Freezable must call this method at the beginning of any API that reads
data members that are not dependency properties. (Inherited
from Freezable.)
Remove Removes a PathFigure object from the collection.
RemoveAt Removes the PathFigure at the specified index position from the collection.
SetCurrentValue Sets the value of a dependency property without changing its value
source. (Inherited fromDependencyObject.)
SetValue(DependencyPropert
y, Object)
Sets the local value of a dependency property, specified by its dependency
property identifier. (Inherited from DependencyObject.)
SetValue(DependencyPropert
yKey, Object)
Sets the local value of a read-only dependency property, specified by
theDependencyPropertyKey identifier of the dependency
197
property. (Inherited fromDependencyObject.)
ShouldSerializeProperty Returns a value that indicates whether serialization processes should
serialize the value for the provided dependency property. (Inherited
from DependencyObject.)
ToString() Converts the current value of a PathFigureCollection to
a String. (OverridesObject.ToString().)
ToString(IFormatProvider) Converts the current value of a PathFigureCollection to a String using the
specified culture-specific formatting information.
VerifyAccess Enforces that the calling thread has access to
this DispatcherObject. (Inherited fromDispatcherObject.)
WritePostscript Raises the Changed event for the Freezable and invokes
its OnChanged method. Classes that derive from Freezable should call this
method at the end of any API that modifies class members that are not
stored as dependency properties. (Inherited from Freezable.)
WritePreamble Verifies that the Freezable is not frozen and that it is being accessed from a
valid threading context. Freezable inheritors should call this method at the
beginning of any API that writes to data members that are not dependency
properties. (Inherited from Freezable.)
Top
Events
Name Description
Changed Occurs when the Freezable or an object it contains is modified. (Inherited from Freezable.)
Top
Extension Methods
Name Description
Aggregate<PathFigure>(Func<PathFig
ure, PathFigure, PathFigure>)
Overloaded. Applies an accumulator function over a
sequence. (Defined byEnumerable.)
Aggregate<PathFigure,
TAccumulate>(TAccumulate,
Func<TAccumulate, PathFigure,
TAccumulate>)
Overloaded. Applies an accumulator function over a sequence.
The specified seed value is used as the initial accumulator
value. (Defined by Enumerable.)
Aggregate<PathFigure, TAccumulate,
TResult>(TAccumulate,
Func<TAccumulate, PathFigure,
TAccumulate>, Func<TAccumulate,
TResult>)
Overloaded. Applies an accumulator function over a sequence.
The specified seed value is used as the initial accumulator value,
and the specified function is used to select the result
value. (Defined by Enumerable.)
198
All<PathFigure> Determines whether all elements of a sequence satisfy a
condition. (Defined byEnumerable.)
Any<PathFigure>() Overloaded. Determines whether a sequence contains any
elements. (Defined byEnumerable.)
Any<PathFigure>(Func<PathFigure,
Boolean>)
Overloaded. Determines whether any element of a sequence
satisfies a condition.(Defined by Enumerable.)
AsEnumerable<PathFigure> Returns the input typed as IEnumerable<T>. (Defined
by Enumerable.)
AsParallel() Overloaded. Enables parallelization of a query. (Defined
by ParallelEnumerable.)
AsParallel<PathFigure>() Overloaded. Enables parallelization of a query. (Defined
by ParallelEnumerable.)
AsQueryable() Overloaded. Converts an IEnumerable to an IQueryable. (Defined
by Queryable.)
AsQueryable<PathFigure>() Overloaded. Converts a generic IEnumerable<T> to a
generic IQueryable<T>. (Defined by Queryable.)
Average<PathFigure>(Func<PathFigur
e, Nullable<Decimal>>)
Overloaded. Computes the average of a sequence of
nullable Decimal values that are obtained by invoking a transform
function on each element of the input sequence.(Defined
by Enumerable.)
Average<PathFigure>(Func<PathFigur
e, Nullable<Double>>)
Overloaded. Computes the average of a sequence of
nullable Double values that are obtained by invoking a transform
function on each element of the input sequence.(Defined
by Enumerable.)
Average<PathFigure>(Func<PathFigur
e, Int32>)
Overloaded. Computes the average of a sequence of Int32 values
that are obtained by invoking a transform function on each
element of the input sequence. (Defined byEnumerable.)
Average<PathFigure>(Func<PathFigur
e, Nullable<Int32>>)
Overloaded. Computes the average of a sequence of
nullable Int32 values that are obtained by invoking a transform
function on each element of the input sequence.(Defined
by Enumerable.)
Average<PathFigure>(Func<PathFigur
e, Int64>)
Overloaded. Computes the average of a sequence of Int64 values
that are obtained by invoking a transform function on each
element of the input sequence. (Defined byEnumerable.)
Average<PathFigure>(Func<PathFigur
e, Nullable<Int64>>)
Overloaded. Computes the average of a sequence of
nullable Int64 values that are obtained by invoking a transform
function on each element of the input sequence.(Defined
by Enumerable.)
199
Average<PathFigure>(Func<PathFigur
e, Single>)
Overloaded. Computes the average of a sequence of Single values
that are obtained by invoking a transform function on each
element of the input sequence. (Defined byEnumerable.)
Average<PathFigure>(Func<PathFigur
e, Nullable<Single>>)
Overloaded. Computes the average of a sequence of
nullable Single values that are obtained by invoking a transform
function on each element of the input sequence.(Defined
by Enumerable.)
Average<PathFigure>(Func<PathFigur
e, Double>)
Overloaded. Computes the average of a sequence
of Double values that are obtained by invoking a transform
function on each element of the input sequence. (Defined
byEnumerable.)
Average<PathFigure>(Func<PathFigur
e, Decimal>)
Overloaded. Computes the average of a sequence
of Decimal values that are obtained by invoking a transform
function on each element of the input sequence. (Defined
byEnumerable.)
Cast<TResult> Converts the elements of an IEnumerable to the specified
type. (Defined byEnumerable.)
Concat<PathFigure> Concatenates two sequences. (Defined by Enumerable.)
Contains<PathFigure>(PathFigure) Overloaded. Determines whether a sequence contains a specified
element by using the default equality comparer. (Defined
by Enumerable.)
Contains<PathFigure>(PathFigure,
IEqualityComparer<PathFigure>)
Overloaded. Determines whether a sequence contains a specified
element by using a specified IEqualityComparer<T>. (Defined
by Enumerable.)
Count<PathFigure>() Overloaded. Returns the number of elements in a
sequence. (Defined by Enumerable.)
Count<PathFigure>(Func<PathFigure,
Boolean>)
Overloaded. Returns a number that represents how many
elements in the specified sequence satisfy a condition. (Defined
by Enumerable.)
DefaultIfEmpty<PathFigure>() Overloaded. Returns the elements of the specified sequence or the
type parameter's default value in a singleton collection if the
sequence is empty. (Defined byEnumerable.)
DefaultIfEmpty<PathFigure>(PathFigur
e)
Overloaded. Returns the elements of the specified sequence or the
specified value in a singleton collection if the sequence is
empty. (Defined by Enumerable.)
Distinct<PathFigure>() Overloaded. Returns distinct elements from a sequence by using
the default equality comparer to compare values. (Defined
by Enumerable.)
Distinct<PathFigure>(IEqualityCompar Overloaded. Returns distinct elements from a sequence by using a
200
er<PathFigure>) specifiedIEqualityComparer<T> to compare values. (Defined
by Enumerable.)
ElementAt<PathFigure> Returns the element at a specified index in a sequence. (Defined
by Enumerable.)
ElementAtOrDefault<PathFigure> Returns the element at a specified index in a sequence or a default
value if the index is out of range. (Defined by Enumerable.)
Except<PathFigure>(IEnumerable<Path
Figure>)
Overloaded. Produces the set difference of two sequences by
using the default equality comparer to compare values. (Defined
by Enumerable.)
Except<PathFigure>(IEnumerable<Path
Figure>,
IEqualityComparer<PathFigure>)
Overloaded. Produces the set difference of two sequences by
using the specifiedIEqualityComparer<T> to compare
values. (Defined by Enumerable.)
First<PathFigure>() Overloaded. Returns the first element of a sequence. (Defined
by Enumerable.)
First<PathFigure>(Func<PathFigure,
Boolean>)
Overloaded. Returns the first element in a sequence that satisfies
a specified condition.(Defined by Enumerable.)
FirstOrDefault<PathFigure>() Overloaded. Returns the first element of a sequence, or a default
value if the sequence contains no elements. (Defined
by Enumerable.)
FirstOrDefault<PathFigure>(Func<Path
Figure, Boolean>)
Overloaded. Returns the first element of the sequence that
satisfies a condition or a default value if no such element is
found. (Defined by Enumerable.)
GroupBy<PathFigure,
TKey>(Func<PathFigure, TKey>)
Overloaded. Groups the elements of a sequence according to a
specified key selector function. (Defined by Enumerable.)
GroupBy<PathFigure,
TKey>(Func<PathFigure, TKey>,
IEqualityComparer<TKey>)
Overloaded. Groups the elements of a sequence according to a
specified key selector function and compares the keys by using a
specified comparer. (Defined byEnumerable.)
GroupBy<PathFigure, TKey,
TElement>(Func<PathFigure, TKey>,
Func<PathFigure, TElement>)
Overloaded. Groups the elements of a sequence according to a
specified key selector function and projects the elements for each
group by using a specified function.(Defined by Enumerable.)
GroupBy<PathFigure, TKey,
TResult>(Func<PathFigure, TKey>,
Func<TKey,
IEnumerable<PathFigure>, TResult>)
Overloaded. Groups the elements of a sequence according to a
specified key selector function and creates a result value from
each group and its key. (Defined byEnumerable.)
GroupBy<PathFigure, TKey,
TElement>(Func<PathFigure, TKey>,
Func<PathFigure, TElement>,
IEqualityComparer<TKey>)
Overloaded. Groups the elements of a sequence according to a
key selector function. The keys are compared by using a
comparer and each group's elements are projected by using a
specified function. (Defined by Enumerable.)
201
GroupBy<PathFigure, TKey,
TResult>(Func<PathFigure, TKey>,
Func<TKey,
IEnumerable<PathFigure>, TResult>,
IEqualityComparer<TKey>)
Overloaded. Groups the elements of a sequence according to a
specified key selector function and creates a result value from
each group and its key. The keys are compared by using a
specified comparer. (Defined by Enumerable.)
GroupBy<PathFigure, TKey, TElement,
TResult>(Func<PathFigure, TKey>,
Func<PathFigure, TElement>,
Func<TKey, IEnumerable<TElement>,
TResult>)
Overloaded. Groups the elements of a sequence according to a
specified key selector function and creates a result value from
each group and its key. The elements of each group are projected
by using a specified function. (Defined by Enumerable.)
GroupBy<PathFigure, TKey, TElement,
TResult>(Func<PathFigure, TKey>,
Func<PathFigure, TElement>,
Func<TKey, IEnumerable<TElement>,
TResult>, IEqualityComparer<TKey>)
Overloaded. Groups the elements of a sequence according to a
specified key selector function and creates a result value from
each group and its key. Key values are compared by using a
specified comparer, and the elements of each group are projected
by using a specified function. (Defined by Enumerable.)
GroupJoin<PathFigure, TInner, TKey,
TResult>(IEnumerable<TInner>,
Func<PathFigure, TKey>,
Func<TInner, TKey>,
Func<PathFigure,
IEnumerable<TInner>, TResult>)
Overloaded. Correlates the elements of two sequences based on
equality of keys and groups the results. The default equality
comparer is used to compare keys. (Defined byEnumerable.)
GroupJoin<PathFigure, TInner, TKey,
TResult>(IEnumerable<TInner>,
Func<PathFigure, TKey>,
Func<TInner, TKey>,
Func<PathFigure,
IEnumerable<TInner>, TResult>,
IEqualityComparer<TKey>)
Overloaded. Correlates the elements of two sequences based on
key equality and groups the results. A
specified IEqualityComparer<T> is used to compare
keys.(Defined by Enumerable.)
Intersect<PathFigure>(IEnumerable<Pa
thFigure>)
Overloaded. Produces the set intersection of two sequences by
using the default equality comparer to compare values. (Defined
by Enumerable.)
Intersect<PathFigure>(IEnumerable<Pa
thFigure>,
IEqualityComparer<PathFigure>)
Overloaded. Produces the set intersection of two sequences by
using the specifiedIEqualityComparer<T> to compare
values. (Defined by Enumerable.)
Join<PathFigure, TInner, TKey,
TResult>(IEnumerable<TInner>,
Func<PathFigure, TKey>,
Func<TInner, TKey>,
Func<PathFigure, TInner, TResult>)
Overloaded. Correlates the elements of two sequences based on
matching keys. The default equality comparer is used to compare
keys. (Defined by Enumerable.)
Join<PathFigure, TInner, TKey,
TResult>(IEnumerable<TInner>,
Func<PathFigure, TKey>,
Func<TInner, TKey>,
Func<PathFigure, TInner, TResult>,
IEqualityComparer<TKey>)
Overloaded. Correlates the elements of two sequences based on
matching keys. A specified IEqualityComparer<T> is used to
compare keys. (Defined by Enumerable.)
202
Last<PathFigure>() Overloaded. Returns the last element of a sequence. (Defined
by Enumerable.)
Last<PathFigure>(Func<PathFigure,
Boolean>)
Overloaded. Returns the last element of a sequence that satisfies a
specified condition.(Defined by Enumerable.)
LastOrDefault<PathFigure>() Overloaded. Returns the last element of a sequence, or a default
value if the sequence contains no elements. (Defined
by Enumerable.)
LastOrDefault<PathFigure>(Func<Path
Figure, Boolean>)
Overloaded. Returns the last element of a sequence that satisfies a
condition or a default value if no such element is found. (Defined
by Enumerable.)
LongCount<PathFigure>() Overloaded. Returns an Int64 that represents the total number of
elements in a sequence. (Defined by Enumerable.)
LongCount<PathFigure>(Func<PathFig
ure, Boolean>)
Overloaded. Returns an Int64 that represents how many elements
in a sequence satisfy a condition. (Defined by Enumerable.)
Max<PathFigure>() Overloaded. Returns the maximum value in a generic
sequence. (Defined byEnumerable.)
Max<PathFigure>(Func<PathFigure,
Nullable<Decimal>>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the maximum
nullable Decimal value. (Defined by Enumerable.)
Max<PathFigure>(Func<PathFigure,
Nullable<Double>>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the maximum
nullable Double value. (Defined by Enumerable.)
Max<PathFigure>(Func<PathFigure,
Int32>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the maximum Int32 value. (Defined
by Enumerable.)
Max<PathFigure>(Func<PathFigure,
Nullable<Int32>>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the maximum nullable Int32 value. (Defined
by Enumerable.)
Max<PathFigure>(Func<PathFigure,
Int64>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the maximum Int64 value. (Defined
by Enumerable.)
Max<PathFigure>(Func<PathFigure,
Nullable<Int64>>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the maximum nullable Int64 value. (Defined
by Enumerable.)
Max<PathFigure>(Func<PathFigure,
Single>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the maximum Single value. (Defined
by Enumerable.)
Max<PathFigure>(Func<PathFigure, Overloaded. Invokes a transform function on each element of a
203
Nullable<Single>>) sequence and returns the maximum
nullable Single value. (Defined by Enumerable.)
Max<PathFigure>(Func<PathFigure,
Double>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the maximum Double value. (Defined
by Enumerable.)
Max<PathFigure>(Func<PathFigure,
Decimal>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the maximum Decimal value. (Defined
by Enumerable.)
Max<PathFigure,
TResult>(Func<PathFigure, TResult>)
Overloaded. Invokes a transform function on each element of a
generic sequence and returns the maximum resulting
value. (Defined by Enumerable.)
Min<PathFigure>() Overloaded. Returns the minimum value in a generic
sequence. (Defined byEnumerable.)
Min<PathFigure>(Func<PathFigure,
Nullable<Decimal>>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the minimum
nullable Decimal value. (Defined by Enumerable.)
Min<PathFigure>(Func<PathFigure,
Nullable<Double>>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the minimum
nullable Double value. (Defined by Enumerable.)
Min<PathFigure>(Func<PathFigure,
Int32>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the minimum Int32 value. (Defined
by Enumerable.)
Min<PathFigure>(Func<PathFigure,
Nullable<Int32>>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the minimum nullable Int32 value. (Defined
by Enumerable.)
Min<PathFigure>(Func<PathFigure,
Int64>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the minimum Int64 value. (Defined
by Enumerable.)
Min<PathFigure>(Func<PathFigure,
Nullable<Int64>>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the minimum nullable Int64 value. (Defined
by Enumerable.)
Min<PathFigure>(Func<PathFigure,
Single>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the minimum Single value. (Defined
by Enumerable.)
Min<PathFigure>(Func<PathFigure,
Nullable<Single>>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the minimum
nullable Single value. (Defined by Enumerable.)
Min<PathFigure>(Func<PathFigure,
Double>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the minimum Double value. (Defined
204
by Enumerable.)
Min<PathFigure>(Func<PathFigure,
Decimal>)
Overloaded. Invokes a transform function on each element of a
sequence and returns the minimum Decimal value. (Defined
by Enumerable.)
Min<PathFigure,
TResult>(Func<PathFigure, TResult>)
Overloaded. Invokes a transform function on each element of a
generic sequence and returns the minimum resulting
value. (Defined by Enumerable.)
OfType<TResult> Filters the elements of an IEnumerable based on a specified
type. (Defined byEnumerable.)
OrderBy<PathFigure,
TKey>(Func<PathFigure, TKey>)
Overloaded. Sorts the elements of a sequence in ascending order
according to a key.(Defined by Enumerable.)
OrderBy<PathFigure,
TKey>(Func<PathFigure, TKey>,
IComparer<TKey>)
Overloaded. Sorts the elements of a sequence in ascending order
by using a specified comparer. (Defined by Enumerable.)
OrderByDescending<PathFigure,
TKey>(Func<PathFigure, TKey>)
Overloaded. Sorts the elements of a sequence in descending order
according to a key.(Defined by Enumerable.)
OrderByDescending<PathFigure,
TKey>(Func<PathFigure, TKey>,
IComparer<TKey>)
Overloaded. Sorts the elements of a sequence in descending order
by using a specified comparer. (Defined by Enumerable.)
Reverse<PathFigure> Inverts the order of the elements in a sequence. (Defined
by Enumerable.)
Select<PathFigure,
TResult>(Func<PathFigure, TResult>)
Overloaded. Projects each element of a sequence into a new
form. (Defined byEnumerable.)
Select<PathFigure,
TResult>(Func<PathFigure, Int32,
TResult>)
Overloaded. Projects each element of a sequence into a new form
by incorporating the element's index. (Defined by Enumerable.)
SelectMany<PathFigure,
TResult>(Func<PathFigure,
IEnumerable<TResult>>)
Overloaded. Projects each element of a sequence to
an IEnumerable<T> and flattens the resulting sequences into one
sequence. (Defined by Enumerable.)
SelectMany<PathFigure,
TResult>(Func<PathFigure, Int32,
IEnumerable<TResult>>)
Overloaded. Projects each element of a sequence to
an IEnumerable<T>, and flattens the resulting sequences into one
sequence. The index of each source element is used in the
projected form of that element. (Defined by Enumerable.)
SelectMany<PathFigure, TCollection,
TResult>(Func<PathFigure, Int32,
IEnumerable<TCollection>>,
Func<PathFigure, TCollection,
TResult>)
Overloaded. Projects each element of a sequence to
an IEnumerable<T>, flattens the resulting sequences into one
sequence, and invokes a result selector function on each element
therein. The index of each source element is used in the
intermediate projected form of that element. (Defined
by Enumerable.)
205
SelectMany<PathFigure, TCollection,
TResult>(Func<PathFigure,
IEnumerable<TCollection>>,
Func<PathFigure, TCollection,
TResult>)
Overloaded. Projects each element of a sequence to
an IEnumerable<T>, flattens the resulting sequences into one
sequence, and invokes a result selector function on each element
therein. (Defined by Enumerable.)
SequenceEqual<PathFigure>(IEnumera
ble<PathFigure>)
Overloaded. Determines whether two sequences are equal by
comparing the elements by using the default equality comparer
for their type. (Defined by Enumerable.)
SequenceEqual<PathFigure>(IEnumera
ble<PathFigure>,
IEqualityComparer<PathFigure>)
Overloaded. Determines whether two sequences are equal by
comparing their elements by using a
specified IEqualityComparer<T>. (Defined by Enumerable.)
Single<PathFigure>() Overloaded. Returns the only element of a sequence, and throws
an exception if there is not exactly one element in the
sequence. (Defined by Enumerable.)
Single<PathFigure>(Func<PathFigure,
Boolean>)
Overloaded. Returns the only element of a sequence that satisfies
a specified condition, and throws an exception if more than one
such element exists. (Defined byEnumerable.)
SingleOrDefault<PathFigure>() Overloaded. Returns the only element of a sequence, or a default
value if the sequence is empty; this method throws an exception if
there is more than one element in the sequence. (Defined
by Enumerable.)
SingleOrDefault<PathFigure>(Func<Pa
thFigure, Boolean>)
Overloaded. Returns the only element of a sequence that satisfies
a specified condition or a default value if no such element exists;
this method throws an exception if more than one element
satisfies the condition. (Defined by Enumerable.)
Skip<PathFigure> Bypasses a specified number of elements in a sequence and then
returns the remaining elements. (Defined by Enumerable.)
SkipWhile<PathFigure>(Func<PathFig
ure, Boolean>)
Overloaded. Bypasses elements in a sequence as long as a
specified condition is true and then returns the remaining
elements. (Defined by Enumerable.)
SkipWhile<PathFigure>(Func<PathFig
ure, Int32, Boolean>)
Overloaded. Bypasses elements in a sequence as long as a
specified condition is true and then returns the remaining
elements. The element's index is used in the logic of the predicate
function. (Defined by Enumerable.)
Sum<PathFigure>(Func<PathFigure,
Nullable<Decimal>>)
Overloaded. Computes the sum of the sequence of
nullable Decimal values that are obtained by invoking a transform
function on each element of the input sequence.(Defined
by Enumerable.)
Sum<PathFigure>(Func<PathFigure,
Nullable<Double>>)
Overloaded. Computes the sum of the sequence of
nullable Double values that are obtained by invoking a transform
function on each element of the input sequence.(Defined
by Enumerable.)
206
Sum<PathFigure>(Func<PathFigure,
Int32>)
Overloaded. Computes the sum of the sequence of Int32 values
that are obtained by invoking a transform function on each
element of the input sequence. (Defined byEnumerable.)
Sum<PathFigure>(Func<PathFigure,
Nullable<Int32>>)
Overloaded. Computes the sum of the sequence of
nullable Int32 values that are obtained by invoking a transform
function on each element of the input sequence.(Defined
by Enumerable.)
Sum<PathFigure>(Func<PathFigure,
Int64>)
Overloaded. Computes the sum of the sequence of Int64 values
that are obtained by invoking a transform function on each
element of the input sequence. (Defined byEnumerable.)
Sum<PathFigure>(Func<PathFigure,
Nullable<Int64>>)
Overloaded. Computes the sum of the sequence of
nullable Int64 values that are obtained by invoking a transform
function on each element of the input sequence.(Defined
by Enumerable.)
Sum<PathFigure>(Func<PathFigure,
Single>)
Overloaded. Computes the sum of the sequence of Single values
that are obtained by invoking a transform function on each
element of the input sequence. (Defined byEnumerable.)
Sum<PathFigure>(Func<PathFigure,
Nullable<Single>>)
Overloaded. Computes the sum of the sequence of
nullable Single values that are obtained by invoking a transform
function on each element of the input sequence.(Defined
by Enumerable.)
Sum<PathFigure>(Func<PathFigure,
Double>)
Overloaded. Computes the sum of the sequence of Double values
that are obtained by invoking a transform function on each
element of the input sequence. (Defined byEnumerable.)
Sum<PathFigure>(Func<PathFigure,
Decimal>)
Overloaded. Computes the sum of the sequence
of Decimal values that are obtained by invoking a transform
function on each element of the input sequence. (Defined
byEnumerable.)
Take<PathFigure> Returns a specified number of contiguous elements from the start
of a sequence.(Defined by Enumerable.)
TakeWhile<PathFigure>(Func<PathFig
ure, Boolean>)
Overloaded. Returns elements from a sequence as long as a
specified condition is true.(Defined by Enumerable.)
TakeWhile<PathFigure>(Func<PathFig
ure, Int32, Boolean>)
Overloaded. Returns elements from a sequence as long as a
specified condition is true. The element's index is used in the
logic of the predicate function. (Defined byEnumerable.)
ToArray<PathFigure> Creates an array from a IEnumerable<T>. (Defined
by Enumerable.)
ToDictionary<PathFigure,
TKey>(Func<PathFigure, TKey>)
Overloaded. Creates a Dictionary<TKey, TValue> from
an IEnumerable<T> according to a specified key selector
function. (Defined by Enumerable.)
207
ToDictionary<PathFigure,
TKey>(Func<PathFigure, TKey>,
IEqualityComparer<TKey>)
Overloaded. Creates a Dictionary<TKey, TValue> from
an IEnumerable<T> according to a specified key selector function
and key comparer. (Defined by Enumerable.)
ToDictionary<PathFigure, TKey,
TElement>(Func<PathFigure, TKey>,
Func<PathFigure, TElement>)
Overloaded. Creates a Dictionary<TKey, TValue> from
an IEnumerable<T> according to specified key selector and
element selector functions. (Defined by Enumerable.)
ToDictionary<PathFigure, TKey,
TElement>(Func<PathFigure, TKey>,
Func<PathFigure, TElement>,
IEqualityComparer<TKey>)
Overloaded. Creates a Dictionary<TKey, TValue> from
an IEnumerable<T> according to a specified key selector
function, a comparer, and an element selector function.(Defined
by Enumerable.)
ToList<PathFigure> Creates a List<T> from an IEnumerable<T>. (Defined
by Enumerable.)
ToLookup<PathFigure,
TKey>(Func<PathFigure, TKey>)
Overloaded. Creates a Lookup<TKey, TElement> from
an IEnumerable<T> according to a specified key selector
function. (Defined by Enumerable.)
ToLookup<PathFigure,
TKey>(Func<PathFigure, TKey>,
IEqualityComparer<TKey>)
Overloaded. Creates a Lookup<TKey, TElement> from
an IEnumerable<T> according to a specified key selector function
and key comparer. (Defined by Enumerable.)
ToLookup<PathFigure, TKey,
TElement>(Func<PathFigure, TKey>,
Func<PathFigure, TElement>)
Overloaded. Creates a Lookup<TKey, TElement> from
an IEnumerable<T> according to specified key selector and
element selector functions. (Defined by Enumerable.)
ToLookup<PathFigure, TKey,
TElement>(Func<PathFigure, TKey>,
Func<PathFigure, TElement>,
IEqualityComparer<TKey>)
Overloaded. Creates a Lookup<TKey, TElement> from
an IEnumerable<T> according to a specified key selector
function, a comparer and an element selector function. (Defined
by Enumerable.)
Union<PathFigure>(IEnumerable<Path
Figure>)
Overloaded. Produces the set union of two sequences by using the
default equality comparer. (Defined by Enumerable.)
Union<PathFigure>(IEnumerable<Path
Figure>,
IEqualityComparer<PathFigure>)
Overloaded. Produces the set union of two sequences by using a
specifiedIEqualityComparer<T>. (Defined by Enumerable.)
Where<PathFigure>(Func<PathFigure,
Boolean>)
Overloaded. Filters a sequence of values based on a
predicate. (Defined byEnumerable.)
Where<PathFigure>(Func<PathFigure,
Int32, Boolean>)
Overloaded. Filters a sequence of values based on a predicate.
Each element's index is used in the logic of the predicate
function. (Defined by Enumerable.)
Zip<PathFigure, TSecond, TResult> Applies a specified function to the corresponding elements of two
sequences, producing a sequence of the results. (Defined
by Enumerable.)
Top
Explicit Interface Implementations
208
Name Description
ICollection.CopyTo Infrastructure. For a description of this member,
see ICollection.CopyTo.
ICollection<PathFigure>.IsReadOnly Infrastructure. For a description of this member,
see ICollection<T>.IsReadOnly.
ICollection.IsSynchronized Infrastructure. For a description of this member,
see ICollection.IsSynchronized.
ICollection.SyncRoot Infrastructure. For a description of this member,
see ICollection.SyncRoot.
IEnumerable<PathFigure>.GetEnumerator Infrastructure. For a description of this member,
see IEnumerable<T>.GetEnumerator.
IEnumerable.GetEnumerator Infrastructure. For a description of this member,
see IEnumerable.GetEnumerator.
IFormattable.ToString Infrastructure. For a description of this member,
see IFormattable.ToString.
IList.Add Infrastructure. For a description of this member,
see IList.Add.
IList.Contains Infrastructure. For a description of this member,
see IList.Contains.
IList.IndexOf Infrastructure. For a description of this member,
see IList.IndexOf.
IList.Insert Infrastructure. For a description of this member,
see IList.Insert.
IList.IsFixedSize Infrastructure. For a description of this member,
see IList.IsFixedSize.
IList.IsReadOnly Infrastructure. For a description of this member,
see IList.IsReadOnly.
IList.Item Infrastructure. For a description of this member,
see IList.Item.
IList.Remove Infrastructure. For a description of this member,
see IList.Remove.
Top
Remarks
209
Except as noted, members of this class behave exactly as described by the IList<T>, ICollection<T>,
and IEnumerable<T> documentation.
Freezable Features: Because it inherits from the Freezable class, the PathFigureCollection class provides several
special features: PathFigureCollection objects can be declared as resources, shared among multiple objects, made
read-only to improve performance, cloned, and made thread-safe. For more information about the different features
provided by Freezable objects, see the Freezable Objects Overview.
Examples
This example shows how to create multiple subpaths in a PathGeometry. To create multiple subpaths, you create
a PathFigure for each subpath.
The following example creates two subpaths, each one a triangle.
XAML <Path Stroke="Black" StrokeThickness="1"> <Path.Data> <PathGeometry> <PathGeometry.Figures> <PathFigureCollection> <PathFigure IsClosed="True" StartPoint="10,100"> <PathFigure.Segments> <PathSegmentCollection> <LineSegment Point="100,100" /> <LineSegment Point="100,50" /> </PathSegmentCollection> </PathFigure.Segments> </PathFigure> <PathFigure IsClosed="True" StartPoint="10,10"> <PathFigure.Segments> <PathSegmentCollection> <LineSegment Point="100,10" /> <LineSegment Point="100,40" /> </PathSegmentCollection> </PathFigure.Segments> </PathFigure> </PathFigureCollection> </PathGeometry.Figures> </PathGeometry> </Path.Data> </Path>
The following example shows how to create multiple subpaths by using a Path and XAML attribute syntax.
Each M creates a new subpath so that the example creates two subpaths that each draw a triangle.
XAML
<Path Stroke="Black" StrokeThickness="1" Data="M 10,100 L 100,100 100,50 Z M 10,10 100,10 100,40 Z" />
(Note that this attribute syntax actually creates a StreamGeometry, a lighter-weight version of a PathGeometry. For
more information, see the Path Markup Syntaxpage.)
210
Version Information
.NET Framework
Supported in: 4, 3.5, 3.0
.NET Framework Client Profile
Supported in: 4, 3.5 SP1
Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows
Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET
Framework System Requirements.
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not
guaranteed to be thread safe.
See Also
Reference
System.Windows.Media Namespace
IList<T>
ICollection<T>
IEnumerable<T>
Other Resources
Freezable Objects Overview