我无法建立一个真正可靠的代码来将矩形居中放在另一个矩形中。
我希望" 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
但它看起来并不干净。
答案 0 :(得分:3)
如果第一个矩形具有坐标(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);
希望这个伪代码有帮助。这主要是一个数学问题。
答案 1 :(得分:0)
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)))
答案 2 :(得分:0)
作为扩展方法:
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)
};
}