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



我有大小为300*200的UserControl。以及尺寸为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();
}

我想像实际结果一样拟合矩形。在此处检查图像

有人能解决这个问题吗。

谢谢。

与其说是编程问题,不如说是数学问题。

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

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();
    }

最新更新