Advertisement Jump to content
Sign in to follow this  

How can i draw rectangles on a WPF Canvas

This topic is 1258 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi guys


first of all thank you for your nice website .


I need help with a problem :  I need to draw rectangles on a Canvas in WPF (C# or VB.NET - Language Doesn't matter)

But only way I know to do that is to define rectangles and add them as children to the canvas.


I want to do it just like GDI+ in Windows Forms , How to do it ??? 

thanks for your help.

Share this post

Link to post
Share on other sites
You make a rectangle and add it to the canvas' children.

var myRect = new System.Windows.Shapes.Rectangle();
myRect.Stroke = System.Windows.Media.Brushes.Black;
myRect.Fill = System.Windows.Media.Brushes.SkyBlue;
myRect.HorizontalAlignment = HorizontalAlignment.Left;
myRect.VerticalAlignment = VerticalAlignment.Center;
myRect.Height = 50;
myRect.Width = 50;

I suspect that using WPF drawing techniques is faster than GDI+ simply because WPF can take advantage of the graphics card to do drawing, as opposed to GDI+ which is bitmap based.

(I have not personally measured them though)

If you really want to use GDI+ like techniques, you can look into using a WPF image control, DrawingVisual, and RenderTargetBitmap as shown here:

    <Image Name="Background"
           HorizontalAlignment="Center" />
Code-behind for the window:
private RenderTargetBitmap buffer;
private DrawingVisual drawingVisual = new DrawingVisual();

public MainWindow()

protected override void OnRender(DrawingContext drawingContext)
    buffer = new RenderTargetBitmap((int)Background.Width, (int)Background.Height, 96, 96, PixelFormats.Pbgra32);
    Background.Source = buffer;

private void DrawStuff()
    if (buffer == null)

    using (DrawingContext drawingContext = drawingVisual.RenderOpen())
        drawingContext.DrawRectangle(new SolidColorBrush(Colors.Red), null, new Rect(0, 0, 10, 10));

(stolen from StackOverflow)

If you really want to use GDI+ itself, you could also look into hosting a Windows Forms control in WPF and drawing on it.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!