【问题标题】:Rotate and Scale rectangle as per user control根据用户控件旋转和缩放矩形
【发布时间】:2016-04-11 06:06:41
【问题描述】:

我有大小为 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

任何人都可以解决这个问题。

谢谢。

【问题讨论】:

  • 它完全按照您的要求做。它旋转。如果你用一张纸来做,你会发现它是一样的。你想要的是我假设的旋转和缩放。
  • @Noctis - 你有什么解决办法吗?
  • 如果您使用的是 WPF,您也可以简单地使用 LayoutTransform 而不是 RenderTransform,并实现相同的效果,减去数学...

标签: c# graphics drawrectangle


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的建议。但是如果矩形的大小发生变化意味着如果它是 300*200。
  • @SagarKhade 那么你需要再次计算它。据我所知,a^2 + b^2 = c^2 仍然是真的 :)
  • 但我的意思是如果用户控件的大小是固定的 300*200。并且矩形也是300*200,角度变为30。那么呢?
  • 您已要求解决当控件为 400x400 且矩形(正方形)为 400x400 的情况时,如果不知道尺寸变化时所需的结果,很难回答。例如,您是否希望矩形被拉伸以使角位于控件的边缘,或者您是否希望保留它的纵横比?请在问题中包含其他案例。
  • 是的,矩形要被拉伸,所以角在控件的边缘,没有其他情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多