0

我有大小为 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();
}

我想像实际结果一样适合矩形。在这里查看图片

任何人都可以对此有解决方案。

谢谢。

4

1 回答 1

2

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

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

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();
    }
于 2016-04-11T06:43:01.693 回答