【问题标题】:Center rectangle in another rectangle在另一个矩形中居中矩形
【发布时间】:2015-01-13 00:11:32
【问题描述】:

我无法建立一个真正可靠的代码来使一个矩形在另一个矩形中居中。

我想让“RectangleToCenter”的中心点与“SourceRectangle”的中心点匹配。 不应涉及缩放。

我目前的尝试是

Public Sub CenterRect(ByVal uMain As Rectangle, ByRef uRectToCenter As Rectangle)

    Dim iAVHeightHalf As Integer = uMain.Height / 2 'src y center
    Dim iAVWidthHalf As Integer = uMain.Width / 2 'src x center

    Dim iStartDestX As Integer = uMain.Left + (uRectToCenter.Width / 2) - iAVWidthHalf
    Dim iStartDestY As Integer = uMain.Top + (uRectToCenter.Height / 2) - iAVHeightHalf

    Dim nNewStart As New Point(iStartDestX, iStartDestY)

    uRectToCenter.Location = nNewStart

End Sub

但我觉得它不干净。

【问题讨论】:

  • 代码看起来不干净,或者结果不是你想要的?

标签: .net vb.net drawing rectangles


【解决方案1】:

如果第一个矩形具有坐标 (x1, y1)、宽度 (w1) 和高度 (h1),则第二个矩形应如下所示:

w2 = //whatever you want the width to be
h2 = //whatever you want the height to be
x2 = x1 + ((w1 - w2) / 2);
y2 = y1 + ((h1 - h2) / 2);

希望这个伪代码有所帮助。这主要是一道数学题。

【讨论】:

    【解决方案2】:
        objSmall.X = CInt(objBig.X + (Math.Round(((objBig.Width / 2) - (objSmall.Width / 2)), 0)))
        objSmall.Y = CInt(objBig.Y + (Math.Round(((objBig.Height / 2) - (objSmall.Height / 2)), 0)))
    

    【讨论】:

    • 这不是只考虑宽高,不考虑物体在屏幕上的位置吗?
    【解决方案3】:

    作为扩展方法:

    public static Point CenterInRectangle(this Size Inner, Rectangle Outer)
    {
        return new Point()
        {
            X = Outer.X + ((Outer.Width - Inner.Width) / 2),
            Y = Outer.Y + ((Outer.Height - Inner.Height) / 2)
        };
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-28
      • 2011-11-24
      • 1970-01-01
      • 2020-07-31
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-20
      相关资源
      最近更新 更多