GDI+ Transormations

  • Thread starter Thread starter Fabio
  • Start date Start date
F

Fabio

Hi all!

A question about transformations.

Let's have this piece of code that transforms the coordinates of the
Graphics object:

---------
Graphics g = e.Graphics;
Matrix m = g.Transform;
m.RotateAt(45, new Point(100, 100));
g.Transform = m;
g.DrawRectangle(Pens.Blue, 50, 50, 100, 100);
---------

This works, ok.
But let's say that I need to get if a point falls into the transformed
rectangle, i.e.:

Rectangle r = new Rectangle(50, 50, 100, 100);
Console.Write(r.Contains(55, 55);

Obviously, this fails, since the point is computed with the "normal"
coordinates.
There is a way to transform also the coordinates of the control surface?

Thanks!
 
A question about transformations.
Let's have this piece of code that transforms the coordinates of the
Graphics object:

---------
Graphics g = e.Graphics;
Matrix m = g.Transform;
m.RotateAt(45, new Point(100, 100));
g.Transform = m;
g.DrawRectangle(Pens.Blue, 50, 50, 100, 100);
---------

This works, ok.
But let's say that I need to get if a point falls into the transformed
rectangle, i.e.:

Rectangle r = new Rectangle(50, 50, 100, 100);
Console.Write(r.Contains(55, 55);

Obviously, this fails, since the point is computed with the "normal"
coordinates.
There is a way to transform also the coordinates of the control surface?



Bob Powell addresses this point in one of his excellent tutorials:

http://www.bobpowell.net/manipulate_graphics.htm
 
Fabio,

Transformations are applied when you draw and they don't affect the data in
the Rectangle object.

I have two suuggestion:
1. Add the rectangle to a GraphicsPath, apply the transformation on the
graphics path (this will modify the coordinates inside the path) and now use
IsVisible or IsOutlineVisible GraphicsPath method to hit test.
2. Create a Matrix that does the oposite inversion (form trasnformed
coorinates to normal (not-trasnformed) and apply the trasnformation on the
the point you want to hittest against and then check with the rectangle.

Matrix m = new Matrix();
m.RotateAt(90, new Point(100, 100));
m.Invert();

Rectangle r = new Rectangle(50, 75, 100, 50);
Point[] pts = new Point[]{new Point(100,50)};
m.TransformPoints(pts);
Console.Write(r.Contains(pts[0]));
 
Back
Top