2008年8月4日 星期一

Rotation in Flex

Rotation is a easy task in Flex. But it's not easy while developing an integrated editing environment. Recently, I was starting to write an editor for photos. I never learned graphics techniques. So, I don't know the vector graphics.

At the first, I found an equation to calculate a rotated point, which is x = dx + x*cos(a) - y*sin(a) and y = dy + x*sin(a) + y*cos(a). That's great. I use it anywhere to calculate a non-rotated point to rotated point. When calculating a rotated point to non-rotated point, I was going to find an equation too, but nothing found. At that time, I felt some thing wrong. Why I could find an equation but not its reverse equation. So, I open my only one book about graphics, Filthy Rich Client. I found I was totally wrong.

Rotation is always done by matrix of affine transform. We can find the equation I found before is the result of applying a rotated and shifted matrix. So, it doesn't need to use math equation to calculate all the time. All you need is just call: transformPoint. If you want to reverse it, just call invese() and then you can have a reversed matrix. It's simple and easy. 

Transform non-rotated to rotated:

var oMx:Matrix = new Matrix();

oMx.rotate(radian);

oMx.translate(dx, dy);

return oMx.transformPoint(new Point(x, y));


The dx and dy is the about point. The x and y is the relative point to the about point. The result of this method is a absolute point.

Transform rotated to non-rotated:

var oMx:Matrix = new Matrix();

oMx.rotate(radian);

oMx.translate(dx, dy);

oMx.invert();

return oMx.transformPoint(new Point(x, y));


The dx and dy is the about point. The x and y is the absolute point. The result of this method is the relative point to the about point.

The following is a sample applying the above functions (two points in the rect are the rotating point.):









 

沒有留言: