Hi everyone. Basically what I'm trying to do is have a picture rotate using mouse events. For example, while you hold down the left mouse button, the picture rotates when you move the mouse up and down. I found another question on here almost like mine (How do I rotate a picture in C#) but when mapping the angle parameter in the rotate method (method source code in link) to the calculated angle between the mouse and the center of the image I get an overflow exception thrown. The image I'm trying to rotate is in a picture box. Any ideas? Should I be doing this another way?
Thanks in advance!
---------EDIT 1-----------
Ok I think my trig was off, I changed it to...
Angle = Atan((mousePosY - imageCenterY)/(mousePosX - imageCenterX)
But now the image doesn't rotate, it just moves (I programmed the ability for it to move as well but that works fine). Here's the piece of code I'm dealing with.
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
isDragging = true;
pbCurrentX = e.X;
pbCurrentY = e.Y;
}
private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
// For moving the image
if (isDragging)
{
this.pictureBox1.Top = this.pictureBox1.Top + (e.Y - pbCurrentY);
this.pictureBox1.Left = this.pictureBox1.Left + (e.X - pbCurrentX);
}
// For rotating the image
if (rotateMode && isDragging)
{
y2 = e.Y;
y1 = (this.pictureBox1.Location.Y + (this.pictureBox1.Height / 2));
x2 = e.X;
x1 = (this.pictureBox1.Location.X + (this.pictureBox1.Width / 2));
angle = (float)Math.Atan((y2-y1)/(x2-x1));
// RotateImage method from the other question linked above
this.pictureBox1.Image = RotateImage(this.pictureBox1.Image, angle);
}
}
The rotateMode flag is set to true when the pictureBox is double clicked. Thanks all!
---------ANSWER-----------
Thanks to Gabe I found all of the little kinks in my code and it works fine now. Only thing is I had to make the size of the picture box larger to fit the rotated image. Here is the correct code for everyone who wants to know the answer.
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
isDragging = true;
pbCurrentX = e.X;
pbCurrentY = e.Y;
}
private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging && !rotateMode)
{
this.pictureBox1.Top = this.pictureBox1.Top + (e.Y - pbCurrentY);
this.pictureBox1.Left = this.pictureBox1.Left + (e.X - pbCurrentX);
}
if (rotateMode && isDragging)
{
y2 = e.Y;
y1 = (this.pictureBox1.Location.Y + (this.pictureBox1.Height / 2));
x2 = e.X;
x1 = (this.pictureBox1.Location.X + (this.pictureBox1.Width / 2));
angle = (float)Math.Atan2((y1 - y2), (x1 - x2));
pictureBox1.Image = RotateImage(currentImage, (100*angle));
}
}
private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
isDragging = false;
}
Thanks Gabe and everyone else!