I want to draw a rectangle onto an Image object that leaves a border of 10 around each side. However, it invariably pushes the rectangle into the upper left corner of the Image.
Here is the code:
DrawingGroup theCanvas = new DrawingGroup();
GeometryDrawing D = new GeometryDrawing(Brushes.LightGray, new Pen(Brushes.Red, 2.0), new RectangleGeometry(new Rect(10, 10, Image_Canvas.Width - 20, Image_Canvas.Height - 20)));
theCanvas.Children.Add(D);
Image_Canvas.Source = new DrawingImage(theCanvas);
The rectangle is being drawn with the correct size, but its upper left corner is (0,0) instead of (10,10). Note that if I add a second rectangle with a white (not null) background with upper left at (0,0) and size equal to the Image's size, then this works.
Is there a way to place an object into an Image at a particular spot, other than starting with a full-size rectangle?
DrawingImage
and DrawingBrush
determine their bounds from the actually drawn components in their Drawing
property, i.e. drawings with a non-null Brush
or Pen
.
So just add a transparent rectangle that covers the whole target area:
var drawing = new DrawingGroup();
var width = Image_Canvas.Width;
var height = Image_Canvas.Height;
drawing.Children.Add(new GeometryDrawing(
Brushes.Transparent,
null,
new RectangleGeometry(new Rect(0, 0, width, height))));
drawing.Children.Add(new GeometryDrawing(
Brushes.LightGray,
new Pen(Brushes.Red, 2.0),
new RectangleGeometry(new Rect(10, 10, width - 20, height - 20))));
Image_Canvas.Source = new DrawingImage(drawing);
You may also want to take a look at DrawingVisual.