Blue Theme Orange Theme Green Theme Red Theme
 
Ads by Lake Quincy Media
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » .NET 3.0/3.5 » Dynamic and static Rectangle in WPF

Dynamic and static Rectangle in WPF

This article shows how to create dynamic and static rectangle in WPF and XAML with various drawing effects.

Author Rank:
Total page views :  12962
Total downloads :  159
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Chapter1.zip
 
Become a Sponsor


In geometry, a rectangle is defined as a quadrilateral where all four of its angles are right angles (90 degrees).

The <Rectangle /> element of XAML draws a rectangle. The Height and Width attributes represent the height and width of the rectangle. The Stroke and Stroke Thickness represents the color and thickness of the rectangle boundary.

In this example, I am showing you how to draw a rectangle static and dynamic. Static rectangle means the rectangle is drawn totally based on XAML code while dynamic rectangle means, I create the rectangle using code in the code behind file.

  1. This code shows how to draw a rectangle:

    <!--static rectangle -->
    <Canvas Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Margin="50,20,0,0">
          <Rectangle Width="150" Height="150" Stroke="Red" Fill="Gray" StrokeThickness="2"></Rectangle>
    </
    Canvas>
    <
    TextBlock Grid.Column="0" Grid.Row="0" HorizontalAlignment="Center">Static Rectangle</TextBlock>

    Draw a rectangle dynamically:

    <!--dynamic rectangle -->
    <Canvas x:Name="canvas" Grid.Column="1" Grid.Row="0" Margin="50,20,0,0"></Canvas>
    <
    TextBlock Grid.Column="1" Grid.Row="0" HorizontalAlignment="Center">Dynamic Rectangle</TextBlock>

    private void DrawRectangle()
    {

                Rectangle exampleRectangle = new Rectangle();
                exampleRectangle.Width = 150;
                exampleRectangle.Height = 150;
                // Create a SolidColorBrush and use it to
                // paint the rectangle.
                SolidColorBrush myBrush = new SolidColorBrush(Colors.Green);
                exampleRectangle.Stroke = Brushes.Red;
                exampleRectangle.StrokeThickness = 4;
                exampleRectangle.Fill = myBrush;
                canvas.Children.Insert(0, exampleRectangle);
     }

    Result looks like this:



    Figure 1.

     

  2. This code shows how draw rectangle with Radius.
     

    <!--static rectangle with radius -->

            <Canvas Grid.Column="0" Grid.Row="1" HorizontalAlignment="Left" Margin="50,20,0,0">

                <Rectangle Width="150" Height="150" RadiusX="10" RadiusY="10" Stroke="Red" Fill="Gray" StrokeThickness="2"></Rectangle>

            </Canvas>

            <TextBlock Grid.Column="0" Grid.Row="1" HorizontalAlignment="Center">Static Rectangle Radius</TextBlock>

    Make dynamically:

    <!--dynamic rectangle with radius -->
            <Canvas x:Name="canvas1" Grid.Column="1" Grid.Row="1" Margin="50,20,0,0"></Canvas>
            <TextBlock Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center">Dynamic Rectangle Radius</TextBlock>

     

    private void RadiusRectangle()

            {

                Rectangle exampleRectangle1 = new Rectangle();

                exampleRectangle1.Width = 150;

                exampleRectangle1.Height = 150;

                exampleRectangle1.RadiusX = 10;

                exampleRectangle1.RadiusY = 10;

                // Create a SolidColorBrush and use it to

                // paint the rectangle.

                SolidColorBrush myBrush = new SolidColorBrush(Colors.Green);

                exampleRectangle1.Stroke = Brushes.Red;

                exampleRectangle1.StrokeThickness = 4;

                exampleRectangle1.Fill = myBrush;

                canvas1.Children.Insert(0, exampleRectangle1);

     

            }

    Result:



    Figure 2.

     

  3. This code shows how to make a rectangle using Gradient colors.
     

    <!--static rectangle with gradient colors-->

            <Canvas Grid.Column="0" Grid.Row="2" HorizontalAlignment="Left" Margin="50,20,0,0">

                <Rectangle Width="150" Height="150">

                  <Rectangle.Fill>

                    <LinearGradientBrush>

                      <GradientStop Color="Yellow" Offset="0.0" />

                      <GradientStop Color="Orange" Offset="0.5" />

                      <GradientStop Color="Red" Offset="1.0" />

                    </LinearGradientBrush>

                  </Rectangle.Fill>

                </Rectangle>

            </Canvas>

            <TextBlock Grid.Column="0" Grid.Row="2" HorizontalAlignment="Center">Static Rectangle Gradient</TextBlock>

    Make Dynamically:
     

    <!--dynamic rectangle with gradient colors-->

            <Canvas x:Name="canvas2" Grid.Column="1" Grid.Row="2" Margin="50,20,0,0"></Canvas>

            <TextBlock Grid.Column="1" Grid.Row="2" HorizontalAlignment="Center">Dynamic Rectangle Gradient</TextBlock>

    private void GradientRectangle()

            {

                Rectangle exampleRectangle = new Rectangle();

                exampleRectangle.Width = 150;

                exampleRectangle.Height = 150;

     

                // Create a RadialGradientBrush and use it to

                // paint the rectangle.

                RadialGradientBrush myBrush = new RadialGradientBrush();

                myBrush.GradientOrigin = new Point(0.75, 0.25);

                myBrush.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));

                myBrush.GradientStops.Add(new GradientStop(Colors.Orange, 0.5));

                myBrush.GradientStops.Add(new GradientStop(Colors.Red, 1.0));

     

                exampleRectangle.Fill = myBrush;

                canvas2.Children.Insert(0, exampleRectangle);

            }



    Figure 3.

     

  4. This code shows how to draw a rectangle paint with an image.

    <!--static paint with image-->

            <Canvas Grid.Column="0" Grid.Row="3" HorizontalAlignment="Left" Margin="50,20,0,0">

                <Rectangle Width="150" Height="150">               

                    <Rectangle.Fill>

                        <ImageBrush ImageSource="sampleImages\san20a.jpg"  />

                    </Rectangle.Fill>

                </Rectangle>

            </Canvas>

            <TextBlock Grid.Column="0" Grid.Row="3" HorizontalAlignment="Center">Static Rectangle paint with image</TextBlock>

    Dynamically:

    <!--dynamic paint with image-->

    <Canvas x:Name="canvas3" Grid.Column="1" Grid.Row="3" Margin="50,20,0,0"></Canvas>

    <TextBlock Grid.Column="1" Grid.Row="3" HorizontalAlignment="Center">Dynamic Rectangle paint with image</TextBlock>

      private void PaintWithImageRectangle()

            {

                Rectangle exampleRectangle = new Rectangle();

                exampleRectangle.Width = 150;

                exampleRectangle.Height = 150;

     

                // Create an ImageBrush and use it to

                // paint the rectangle.

                ImageBrush myBrush = new ImageBrush();

                myBrush.ImageSource =

                    new BitmapImage(new Uri(@"C:\Users\Raj\Documents\Visual Studio 2008\Projects\Chapter1\Chapter1\sampleImages\san20a.jpg", UriKind.Relative));

     

                exampleRectangle.Fill = myBrush;

                canvas3.Children.Insert(0, exampleRectangle);

            }

    Result:



    Figure 4.
     

  5. This code shows how to draw paint a rectangle with visual effects.

    <!--static paint with visual-->

            <Canvas Grid.Column="2" Grid.Row="0" HorizontalAlignment="Left" Margin="50,20,0,0">

                <Rectangle Width="150" Height="150" Stroke="Red" StrokeThickness="4">

                    <Rectangle.Fill>

                        <VisualBrush TileMode="Tile">

                            <VisualBrush.Visual>

                                <StackPanel>

                                    <StackPanel.Background>

                                        <DrawingBrush>

                                            <DrawingBrush.Drawing>

                                                <GeometryDrawing>

                                                    <GeometryDrawing.Brush>

                                                        <RadialGradientBrush>

                                                            <GradientStop Color="MediumBlue" Offset="0.0" />

                                                            <GradientStop Color="White" Offset="1.0" />

                                                        </RadialGradientBrush>

                                                    </GeometryDrawing.Brush>

                                                    <GeometryDrawing.Geometry>

                                                        <GeometryGroup>

                                                            <RectangleGeometry Rect="0,0,50,50" />

                                                            <RectangleGeometry Rect="50,50,50,50" />

                                                        </GeometryGroup>

                                                    </GeometryDrawing.Geometry>

                                                </GeometryDrawing>

                                            </DrawingBrush.Drawing>

                                        </DrawingBrush>

                                    </StackPanel.Background>

                                    <TextBlock FontSize="10pt" Margin="10">Raj Beniwal</TextBlock>

                                </StackPanel>

                            </VisualBrush.Visual>

                        </VisualBrush>

                    </Rectangle.Fill>

                </Rectangle>

            </Canvas>

            <TextBlock Grid.Column="2" Grid.Row="0" HorizontalAlignment="Center">Static Rectangle paint with visual</TextBlock>

    Dynamically:
     

    <!--dynamic paint with image-->

    <Canvas x:Name="canvas4" Grid.Column="3" Grid.Row="0" Margin="50,20,0,0"></Canvas>

    <TextBlock Grid.Column="3" Grid.Row="0" HorizontalAlignment="Center">Dynamic Rectangle paint with visual</TextBlock>

    private void VisualRectangle()

            {

                Rectangle exampleRectangle = new Rectangle();

                exampleRectangle.Width = 150;

                exampleRectangle.Height = 150;

                exampleRectangle.StrokeThickness = 4;

                exampleRectangle.Stroke = Brushes.Red;

     

                // Create a VisualBrush and use it

                // to paint the rectangle.

                VisualBrush myBrush = new VisualBrush();

     

                //

                // Create the brush's contents.

                //

                StackPanel aPanel = new StackPanel();

     

                // Create a DrawingBrush and use it to

                // paint the panel.

                DrawingBrush myDrawingBrushBrush = new DrawingBrush();

                GeometryGroup aGeometryGroup = new GeometryGroup();

                aGeometryGroup.Children.Add(new RectangleGeometry(new Rect(0, 0, 50, 50)));

                aGeometryGroup.Children.Add(new RectangleGeometry(new Rect(50, 50, 50, 50)));

                RadialGradientBrush checkerBrush = new RadialGradientBrush();

                checkerBrush.GradientStops.Add(new GradientStop(Colors.Green, 0.0));

                checkerBrush.GradientStops.Add(new GradientStop(Colors.White, 1.0));

                GeometryDrawing checkers = new GeometryDrawing(checkerBrush, null, aGeometryGroup);

                myDrawingBrushBrush.Drawing = checkers;

                aPanel.Background = myDrawingBrushBrush;

     

                // Create some text.

                TextBlock someText = new TextBlock();

                someText.Text = "Raj Beniwal";

                FontSizeConverter fSizeConverter = new FontSizeConverter();

                someText.FontSize = (double)fSizeConverter.ConvertFromString("10pt");

                someText.Margin = new Thickness(10);

     

                aPanel.Children.Add(someText);

     

                myBrush.Visual = aPanel;

                exampleRectangle.Fill = myBrush;

                canvas4.Children.Insert(0, exampleRectangle);

     

            }



    Figure 5.
     

  6. This code shows how to draw and paint a rectangle with drawing brush.

    <!--static paint with drawing-->

            <Canvas Grid.Column="2" Grid.Row="1" HorizontalAlignment="Left" Margin="50,20,0,0">

                <Rectangle Width="150" Height="150">

                    <Rectangle.Fill>

                        <DrawingBrush Viewport="0,0,0.25,0.25" TileMode="Tile">

                            <DrawingBrush.Drawing>

                                <DrawingGroup>

                                    <GeometryDrawing Brush="White">

                                        <GeometryDrawing.Geometry>

                                            <RectangleGeometry Rect="0,0,100,100" />

                                        </GeometryDrawing.Geometry>

                                    </GeometryDrawing>

     

                                    <GeometryDrawing>

                                        <GeometryDrawing.Geometry>

                                            <GeometryGroup>

                                                <RectangleGeometry Rect="0,0,50,50" />

                                                <RectangleGeometry Rect="50,50,50,50" />

                                            </GeometryGroup>

                                        </GeometryDrawing.Geometry>

                                        <GeometryDrawing.Brush>

                                            <LinearGradientBrush>

                                                <GradientStop Offset="0.0" Color="Red" />

                                                <GradientStop Offset="1.0" Color="Green" />

                                            </LinearGradientBrush>

                                        </GeometryDrawing.Brush>

                                    </GeometryDrawing>

                                </DrawingGroup>

                            </DrawingBrush.Drawing>

                        </DrawingBrush>

                    </Rectangle.Fill>

                </Rectangle>

            </Canvas>

            <TextBlock Grid.Column="2" Grid.Row="1" HorizontalAlignment="Center">Static Rectangle paint with drawing</TextBlock>

    Dynamic:
     

    <!--dynamic paint with drawing-->

    <Canvas x:Name="canvas5" Grid.Column="3" Grid.Row="1" Margin="50,20,0,0"></Canvas>

    <TextBlock Grid.Column="3" Grid.Row="1" HorizontalAlignment="Center">Dynamic Rectangle paint with drawing</TextBlock>

    private void PaintWithDrawing()

            {

                Rectangle exampleRectangle = new Rectangle();

                exampleRectangle.Width = 150;

                exampleRectangle.Height = 150;

     

                // Create a DrawingBrush and use it to

                // paint the rectangle.

                DrawingBrush myBrush = new DrawingBrush();

     

                GeometryDrawing backgroundSquare =

                    new GeometryDrawing(

                        Brushes.White,

                        null,

                        new RectangleGeometry(new Rect(0, 0, 100, 100)));

     

                GeometryGroup aGeometryGroup = new GeometryGroup();

                aGeometryGroup.Children.Add(new RectangleGeometry(new Rect(0, 0, 50, 50)));

                aGeometryGroup.Children.Add(new RectangleGeometry(new Rect(50, 50, 50, 50)));

     

                LinearGradientBrush checkerBrush = new LinearGradientBrush();

                checkerBrush.GradientStops.Add(new GradientStop(Colors.Red, 0.0));

                checkerBrush.GradientStops.Add(new GradientStop(Colors.Green, 1.0));

     

                GeometryDrawing checkers = new GeometryDrawing(checkerBrush, null, aGeometryGroup);

     

                DrawingGroup checkersDrawingGroup = new DrawingGroup();

                checkersDrawingGroup.Children.Add(backgroundSquare);

                checkersDrawingGroup.Children.Add(checkers);

     

                myBrush.Drawing = checkersDrawingGroup;

                myBrush.Viewport = new Rect(0, 0, 0.25, 0.25);

                myBrush.TileMode = TileMode.Tile;

     

                exampleRectangle.Fill = myBrush;

                canvas5.Children.Insert(0, exampleRectangle);

            }

    Result:



    Figure 6.

     

  7. This code shows how to draw and fill a rectangle with a brush and opacity (transparency). The Opacity property defines the transparency of a control in XAML and WPF.

    <!--static rectangle with brush -->

            <Canvas Grid.Column="2" Grid.Row="2" HorizontalAlignment="Left" Margin="50,20,0,0">

                <Rectangle Width="150" Height="150">

                    <Rectangle.Fill>

                        <SolidColorBrush Color="Green" Opacity="0.25" />

                    </Rectangle.Fill>

                </Rectangle>

            </Canvas>

            <TextBlock Grid.Column="2" Grid.Row="2" HorizontalAlignment="Center">Static Rectangle rectangle with brush</TextBlock>

    Dynamic:
     

    <!--dynamic rectangle using brush-->

            <Canvas x:Name="canvas6" Grid.Column="3" Grid.Row="2" Margin="50,20,0,0"></Canvas>

            <TextBlock Grid.Column="3" Grid.Row="2" HorizontalAlignment="Center">Dynamic Rectangle paint with drawing</TextBlock>

    private void RectangleWithBrush()

            {

                Rectangle myRectangle = new Rectangle();

                myRectangle.Width = 150;

                myRectangle.Height = 150;

                SolidColorBrush partiallyTransparentSolidColorBrush

                    = new SolidColorBrush(Colors.Green);

                partiallyTransparentSolidColorBrush.Opacity = 0.25;

                myRectangle.Fill = partiallyTransparentSolidColorBrush;

                canvas6.Children.Insert(0, myRectangle);

     

            }

    Result:



    Figure 7.

     

  8. This demonstrate how to rotate a rectangle using transformation. The RenderTransform property of Rectangle is responsible for transforming a rectangle such as rotating.
     

    <!--static rotate rectangle -->

            <Canvas Grid.Column="2" Grid.Row="3" HorizontalAlignment="Left" Margin="50,20,0,0">

                <Rectangle Width="150" Height="150" Stroke="#FFBF4343" Canvas.Left="10" Canvas.Top="10" StrokeThickness="4" RenderTransformOrigin="0.5,0.5">

                    <Rectangle.RenderTransform>

                        <TransformGroup>

                            <ScaleTransform ScaleX="1" ScaleY="1"/>

                            <SkewTransform AngleX="0" AngleY="0"/>

                            <RotateTransform Angle="30.704"/>

                            <TranslateTransform X="0" Y="0"/>

                        </TransformGroup>

                    </Rectangle.RenderTransform>

                    <Rectangle.Fill>

                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

                            <GradientStop Color="#FF000000" Offset="0"/>

                            <GradientStop Color="#FF1E1919" Offset="1"/>

                        </LinearGradientBrush>

                    </Rectangle.Fill>

                </Rectangle>

            </Canvas>

            <TextBlock Grid.Column="2" Grid.Row="3" HorizontalAlignment="Center">Static Rotate Rectangle</TextBlock>

    Result:


    Figure 8.

For more information see attached project. This is it.


Login to add your contents and source code to this article
 About the author
 
Raj Kumar
Rajkumar is working as a senior software engineer has over 5 years experience working on ASP.NET, VB.NET, C#, AJAX and other latest technologies. He holds Master's degree in Computer Science. currently enjoying working on WPF, WCF, Silverlight, MVC, XAML.I can be reached on at raj2511984 at yahoo.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Chapter1.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
good article by reena On August 31, 2008
good research raj beniwal. 10/10 points for you
Reply | Email | Delete | Modify | 
Re: good article by Raj On September 1, 2008
thank you very much
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.