Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a rectangle on a WPF canvas

Tags:

c#

canvas

wpf

I'm trying to draw a Rectangle on a Canvas as follows:

System.Windows.Shapes.Rectangle rect;
rect = new System.Windows.Shapes.Rectangle();
rect.Stroke = new SolidColorBrush(Colors.Black);
rect.Fill = new SolidColorBrush(Colors.Black);
rect.Width=200;
rect.Height=200;
Canvas.SetLeft(rect,0);
Canvas.SetTop(rect,0);
front_canvas.Children.Add(rect);

Why would this code not draw a rectangle?

The canvas is defined in the associated XAML as follows:

<Canvas Height="200" Width="200" Name="front_canvas" Grid.Row="1" Grid.Column="0">      
</Canvas>

The canvas shows up fine. I can tell because of the gap it leaves in the layout grid.

like image 337
Sheena Avatar asked Feb 08 '13 22:02

Sheena


People also ask

How do you draw a square in XAML?

Creating a RectangleThe Rectangle element in XAML creates a rectangle shape. The following code snippet creates a rectangle by setting its width and height properties to 200 and 100 respectively. The code also sets the black stroke of width 4.

How do I draw a line in canvas WPF?

To draw a line, create a Line element. Use its X1 and Y1 properties to set its start point; and use its X2 and Y2 properties to set its end point. Finally, set its Stroke and StrokeThickness because a line without a stroke is invisible. Setting the Fill element for a line has no effect, because a line has no interior.

How do you draw a circle in WPF?

Use its Stroke property to specify the Brush that is used to paint the outline of the ellipse. The StrokeThickness property specifies the thickness of the ellipse outline. To draw a circle, make the Width and Height of the Ellipse element equal to each other.


1 Answers

This should draw your rectangle as a 200x200 black square, provided front_canvas is displayed correctly.

Why would this code not draw a rectangle?

The main reasons this would not draw are:

  • front_canvas is not visible
  • front_canvas is not in the visual tree and being displayed correctly
  • Some other FrameworkElement is obscuring front_canvas, at least the upper left corner.
  • There is another object in the canvas at a higher z order.

Note that you'd typically also want to set StrokeThickness if you want to see the Stroke you specify.

like image 69
Reed Copsey Avatar answered Sep 25 '22 13:09

Reed Copsey