1

I have a DrawingVisual like this:

Rect MyRect = new Rect(new Point(0, 0), new Size(100, 100));
DrawingVisual MyVisual = new DrawingVisual();

using (DrawingContext context = MyVisual.RenderOpen()) {
context.DrawRectangle(Brushes.Black, new Pen(), MyRect);
context.PushTransform(new TranslateTransform(50, 50));
context.PushTransform(new ScaleTransform(2, 2));
}

I want to get the Geometry which describes the area of the element, in this case a RectangleGeometry where Rect property is:

Rect(new Point(50, 50), new Size(200, 200))

Thanks.

gliderkite
  • 8,828
  • 6
  • 44
  • 80

1 Answers1

3

If you would push the transforms before drawing the Rect, you could get the proper bounds by the ContentBounds property:

Rect rect = new Rect(new Size(100, 100));

using (DrawingContext dc = visual.RenderOpen())
{
    dc.PushTransform(new TranslateTransform(50, 50));
    dc.PushTransform(new ScaleTransform(2, 2));
    dc.DrawRectangle(Brushes.Black, null, rect);
}

System.Diagnostics.Trace.TraceInformation("Bounds = {0}", visual.ContentBounds);

From the Remarks section in PushTransform:

The transform applies to all subsequent drawing commands until it is removed by the Pop command.

Clemens
  • 123,504
  • 12
  • 155
  • 268
  • seems to work, but there are some cases in my application where there's a strange behavior (the result is {0,0,300,300}). See [my question](http://stackoverflow.com/questions/10451066/visuals-hit-testing) please. – gliderkite May 04 '12 at 14:48
  • Changed the answer to use ContentBounds instead of DescendantBounds. Sorry, but i confused the two. Does that make any difference? – Clemens May 04 '12 at 15:28
  • I'll try, I have to solve the problem of the other parallel question. – gliderkite May 04 '12 at 15:31