我的表单上有两个点,还有一个图片框,如下所示:
*
[^]
[ ]
*
Run Code Online (Sandbox Code Playgroud)
我想将图片框与点对齐,这样它看起来像这样:
*
\^\
\ \
*
Run Code Online (Sandbox Code Playgroud)
我如何计算角度以及如何旋转PictureBox?
目前我正在使用这个:
double xDifference = Math.Abs(point2.X - point1.X);
double yDifference = Math.Abs(point2.Y - point1.Y);
double angle = Math.Atan(yDifference / xDifference) * 180 / Math.PI;
Run Code Online (Sandbox Code Playgroud)
但是这不起作用,因为x和y值是绝对的,因此如果点2留在点1,它们就无法计算它.
为了旋转图像,我发现了以下功能:
public Bitmap rotateImage(Image image, PointF offset, float angle) {
// Create a new empty bitmap to hold rotated image
Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
// Make a graphics object from the empty bitmap
Graphics g = Graphics.FromImage(rotatedBmp);
// Put the rotation point in the center of the image
g.TranslateTransform(offset.X, offset.Y);
// Rotate the image
g.RotateTransform(angle);
// Move the image back
g.TranslateTransform(-offset.X, -offset.Y);
// Draw passed in image onto graphics object
g.DrawImage(image, new PointF(0, 0));
return rotatedBmp;
}
Run Code Online (Sandbox Code Playgroud)
我该如何使用该功能?我不确定要为偏移量插入什么值.
谢谢
让我们把所有的计算放在一起。
首先,连接两点的线的方向可以计算为
double xDifference = point2.X - point1.X;
double yDifference = point2.Y - point1.Y;
double angleRadians = Math.Atan2(yDifference, xDifference);
Run Code Online (Sandbox Code Playgroud)
那么旋转后垂直方向(90度)一定与上面考虑的方向平行,所以旋转角度为
double rotationAngleRadians = angleDegrees - Math.PI/2;
Run Code Online (Sandbox Code Playgroud)
有了这个角度,我们就可以计算边界框的大小:
double newWidth = image.Width * Math.Abs(Math.Cos(rotationAngleRadians)) +
image.Height * Math.Abs(Math.Sin(rotationAngleRadians));
double newHeight = image.Width * Math.Abs(Math.Sin(rotationAngleRadians)) +
image.Height * Math.Abs(Math.Cos(rotationAngleRadians));
Run Code Online (Sandbox Code Playgroud)
现在,我们首先需要进行变换,使旧图像的中间位于位置 0。这使得平移变换为(-image.Width/2, -image.Height/2)。然后,我们应用旋转rotationAngleDegrees(即rotationAngleRadians * 180 / Math.PI),因为Graphics' 旋转需要以度为单位的角度。然后,我们将图像移动到新图像的中间,即平移变换(newWidth/2, newHeight/2)。