Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I dispose() the Matrix returned by Graphics.Transform?

Tags:

c#

graphics

I need to draw primitives with graphics object with different transformation matrix. I wonder should I dispose the matrix or graphics will do it for me:

using (var g = Graphics.FromImage(...))
{
    ... some code ...
    var tmp = g.Transform;
    g.TranslateTransform(...);
    ... some code ...
    g.Transform = tmp;
    // should I call tmp.Dispose() here?
    tmp.Dispose();
    ... some code that use g ....
}

http://msdn.microsoft.com/en-us/library/system.drawing.graphics.transform.aspx

Says:

Because the matrix returned and by the Transform property is a copy of the geometric transform, you should dispose of the matrix when you no longer need it.

I do not need it after g.Transform = tmp;, should I dispose it?

like image 383
Alex Netkachov Avatar asked Jul 01 '11 15:07

Alex Netkachov


2 Answers

Quoting MSDN, Graphics.Transform...

Gets or sets a copy of the geometric world transformation for this Graphics.

(emphasis mine.)

When you call Transform, you're making a copy of the Matrix, and you should dispose it yourself. As long as you own them, it's always a good idea to dispose objects that implement IDisposable, and preferably using the using(...) syntax.

like image 157
razlebe Avatar answered Nov 19 '22 21:11

razlebe


Looking through Reflector I see that the Matrix struct has a reference to the native matrix

public sealed class Matrix : MarshalByRefObject, IDisposable
{
    // Fields
    internal IntPtr nativeMatrix;
...

and when Disposed() is called

private void Dispose(bool disposing)
{
    if (this.nativeMatrix != IntPtr.Zero)
    {
        SafeNativeMethods.Gdip.GdipDeleteMatrix(new HandleRef(this, this.nativeMatrix));
        this.nativeMatrix = IntPtr.Zero;
    }
}

So the answer would be a definite yes.

like image 40
John Alexiou Avatar answered Nov 19 '22 20:11

John Alexiou