WPF Graphics: Drawing a circle with code

This entry is part 5 of 8 in the series WPF Graphics

If you have like to use the traditional method to draw a circle instead of using XAML.

Notice that I did not declare a Stackpanel in the xaml.  The stackpanel is displayed using

this.Content = stack;

MainWindow.xaml.cs

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WpfApplication10
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        void OnLoad(object sender, RoutedEventArgs e)
        {
            StackPanel stack = new StackPanel();

            // Create a red Ellipse.
            Ellipse ellipse = new Ellipse();

            // Create a SolidColorBrush with a yellow color to fill the 
            // Ellipse with.
            SolidColorBrush colorBrush = new SolidColorBrush();

            // Describes the brush's color using RGB values. 
            // Each value has a range of 0-255.
            colorBrush.Color = Color.FromArgb(255, 255, 255, 0);
            ellipse.Fill = colorBrush;
            ellipse.StrokeThickness = 2;
            ellipse.Stroke = Brushes.Black;

            // Set the width and height of the Ellipse.
            ellipse.Width = 250;
            ellipse.Height = 250;

            // Add the Ellipse to the StackPanel.
            stack.Children.Add(ellipse);

            this.Content = stack;
        }

    }
}

MainWindow.xaml

<Window x:Class="WpfApplication10.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication10"
        mc:Ignorable="d"
        Loaded="OnLoad"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

    </Grid>
</Window>

circle1

Series Navigation<< WPF Graphics: Drawing a circle
WPF Graphics: Drawing a square using XAML >>

Leave a comment

Leave a Reply