Introduction
We all are familiar with 2D arrays in C#, every element is accessed by 2 points.
In the same way 2D graphics has elements much like shapes, where every point has 2 coordinates, X & Y. So if you want to draw a line you'll need 2 vertices, and each vertex will have 2 coordinates on the graph. e.g. point1 = 30,10 point2 = 220,10.
This will draw a straight line.
2D graphics in WPF
WPF provides various shapes & drawings to generate 2D graphics.
We will learn shapes such as Line, Ellipse, Rectangle, Path, Polyline & Polygon.
Without further ado let's learn them one by one.
Line
In order to draw a line in WPF we can use Line element.
It has properties such as X1,Y1 & X2,Y2. Use its X1 and Y1 properties to set its start point & X2 and Y2 properties to set its endpoint of the line.
Now you have set the points right, but we have to make the line visible as well, for that, we need to set its Stroke and StrokeThickness properties.
- <!-- 1. Line -->
- <Line x:Name="TwoDLine"
- X1="30" Y1="10"
- X2="220" Y2="10"
- Stroke="DarkGray"
- StrokeThickness="2"/>
Output
Ellipse
To draw an ellipse, we must use the Ellipse element and specify its Width and Height. If you want its interior to be painted then you can use Fill property to specify the Brush. For setting up its border we can use its Stroke property to specify the Brush. The StrokeThickness property specifies the thickness of the ellipse's border.
- <!-- 2. Ellipse -->
- <Ellipse x:Name="TwoDEllipse"
- Width = "75"
- Height = "45"
- Stroke="DarkGray"
- Margin="10 0 0 0"
- StrokeThickness="1">
- <Ellipse.Fill>
- <RadialGradientBrush>
- <GradientStop Offset = "0" Color = "AliceBlue"/>
- <GradientStop Offset = "1" Color = "LightBlue"/>
- <GradientStop Offset = "2" Color = "DarkBlue"/>
- </RadialGradientBrush>
- </Ellipse.Fill>
- </Ellipse>

Rectangle
To draw a rectangle, we have a Rectangle element and same as ellipse we can specify its Width and Height.
If you want its interior to be painted then you can use Fill property to specify the Brush. For setting up its border we can use its Stroke property to specify the Brush. The StrokeThickness property specifies the thickness of the rectangle's border.
- <!-- 3. Rectangle -->
- <Rectangle x:Name="TwoDRectangle"
- Width="75"
- Height="45"
- Margin = "10 0 0 0"
- Fill="LightBlue"
- Stroke="DarkGray"
- StrokeThickness="1"/>
Output

We can also have a rectangle with rounded corners, specify RadiusX and RadiusY properties.
- <!-- 3. Rectangle with Rounded corners -->
- <Rectangle x:Name="TwoDRectangle"
- Width="75"
- Height="45"
- Margin = "10 0 0 0"
- Fill="LightBlue"
- Stroke="DarkGray"
- StrokeThickness="1"
- RadiusX="10"
- RadiusY="10"/>






Join the conversation! Your thoughts help the community grow.