views:

331

answers:

1

I need to be able to rotate an image around a given point so that what ever part of the image appears in the center of my container is the center of rotation.

To calculate the center points, I am currently just taking the inverse of the translation applied to the image:

Rotate.CenterX = Translate.X * -1;
Rotate.CenterY = Translate.Y * -1;

However, the current calculation i'm using is not sufficient as it does not work if the image has been translated after being rotated.

I'm sure it's a reasonably straight forward trig function, I just can't think what it is!

Cheers

A: 

If you are working with GDI+ then use the following:

double ImWidth = (double)Im.Width;
double ImHeight = (double)Im.Height;
double XTrans = -(ImWidth * X);
double YTrans = -(ImHeight * Y);

g.TranslateTransform((float)XTrans, (float)YTrans);    
g.TranslateTransform((float)(ImWidth / 2.0 - XTrans), (float)(ImHeight / 2.0 - YTrans));
g.RotateTransform((float)Angle);
g.TranslateTransform(-((float)(ImWidth / 2.0 - XTrans)), -((float)(ImHeight / 2.0 - YTrans)));

If you are working with WPF graphic objects, use the following transform group:

TransformGroup TC = new TransformGroup();
RotateTransform RT = new RotateTransform(Angle);
RT.CenterX = Im.Width / 2.0;
RT.CenterY = Im.Height / 2.0;
TranslateTransform TT = new TranslateTransform(-X * Im.PixelWidth, -Y * Im.PixelHeight);
TC.Children.Add(TT);
TC.Children.Add(RT);

X & Y are the percent values you want to translate the image in (if the image is 1000 pixels and X is 0.1 then the image will be translated 100 pixels). This is how I needed the function to work but you can easily change it otherwise.

Gilad
Thanks for your answer! The problem I was having seemed largely due to the way I was dealing with the individual Transforms (I added one of each then modified them rather than accumulating multiple Transforms). I'm not quite there yet, but I'm closer now and with much less code!
Tom Allen