根据用户控件旋转和缩放矩形

Rotate and Scale rectangle as per user control

我有大小为 300*200 的用户控件。 和大小为 300*200 的矩形。

graphics.DrawRectangle(Pens.Black, 0, 0, 300, 200);

当我在 userControl 中将矩形旋转 30 度时,我得到了旋转的矩形,但它变大了。

PointF center = new PointF(150,100);
graphics.FillRectangle(Brushes.Black, center.X, center.Y, 2, 2); // draw center point.

using (Matrix matrix = new Matrix())
{
      matrix.RotateAt(30, center);
      graphics.Transform = matrix;
      graphics.DrawRectangle(Pens.Black, 0, 0, 300, 200);
      graphics.ResetTransform();
}

我想像实际结果一样拟合矩形。Check Image here

谁能解决这个问题。

谢谢。

这更像是一道数学题,而不是编程题。

计算以弧度为单位旋转任意角度的任意矩形的边界框。

var newWidth= Math.Abs(height*Math.Sin(angle)) + Math.Abs(width*Math.Cos(angle))
var newHeight= Math.Abs(width*Math.Sin(angle)) + Math.Abs(height*Math.Cos(angle))

计算 x 和 y 的比例:

scaleX = width/newWidth;
scaleY = height/newHeight;

将其应用于您的矩形。

编辑: 应用于您的示例:

    PointF center = new PointF(150, 100);
    graphics.FillRectangle(Brushes.Black, center.X, center.Y, 2, 2); // draw center point.
    var height = 200;
    var width = 300;
    var angle = 30;
    var radians = angle * Math.PI / 180;
    var boundingWidth = Math.Abs(height * Math.Sin(radians)) + Math.Abs(width * Math.Cos(radians));
    var boundingHeight = Math.Abs(width * Math.Sin(radians)) + Math.Abs(height * Math.Cos(radians));
    var scaleX = (float)(width / boundingWidth);
    var scaleY = (float)(height / boundingHeight);
    using (Matrix matrix = new Matrix())
    {
        matrix.Scale(scaleX, scaleY, MatrixOrder.Append);
        matrix.Translate(((float)boundingWidth - width) / 2, ((float)boundingHeight - height) / 2);
        matrix.RotateAt(angle, center);
        graphics.Transform = matrix;
        graphics.DrawRectangle(Pens.Black, 0, 0, width, height);
        graphics.ResetTransform();
    }