I am drawing a rectangle in a WinForms application in C# and I want to get the actual coordinates of the rectangle after applying ScaleTransform()
method.
Graphics g = e.Graphics;
g.ScaleTransform(2.0F,2.0F,System.Drawing.Drawing2D.MatrixOrder.Append);
g.DrawRectangle(pen, 20, 40, 100,100)
Once you have set a ScaleTransform
in your Graphics
object (or any transform for that matter), you can use it to transform the points of your rectangle (or any other points).
For example:
// your existing code
Graphics g = e.Graphics;
g.ScaleTransform(2.0F,2.0F,System.Drawing.Drawing2D.MatrixOrder.Append);
// say we have some rectangle ...
Rectangle rcRect = new Rectangle(20, 40, 100, 100);
// make an array of points
Point[] pPoints =
{
new Point(rcRect.Left, rcRect.Top), // top left
new Point(rcRect.Right, rcRect.Top), // top right
new Point(rcRect.Left, rcRect.Bottom), // bottom left
new Point(rcRect.Right, rcRect.Bottom), // bottom right
};
// get a copy of the transformation matrix
using (Matrix mat = g.Transform)
{
// use it to transform the points
mat.TransformPoints(pPoints);
}
Note the using
syntax above - this is because, as MSDN 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.
As a slightly less wordy alternative, you can do the same thing using the TransformPoints
method of the Graphics
class (MSDN here) - so construct your array of points as above, then just do this:
g.TransformPoints(CoordinateSpace.Page, CoordinateSpace.World, pPoints);
MSDN describes the relevant coordinate spaces used in the above function:
GDI+ uses three coordinate spaces: world, page, and device. World coordinates are the coordinates used to model a particular graphic world and are the coordinates you pass to methods in the .NET Framework. Page coordinates refer to the coordinate system used by a drawing surface, such as a form or a control. Device coordinates are the coordinates used by the physical device being drawn on, such as a screen or a printer. The Transform property represents the world transformation, which maps world coordinates to page coordinates.