确定矩形的中心点并将新矩形移动到中心

Determining Center point of a Rectangle and move New Rectangle to the Center

我以编程方式在 Image.The 上为用户提供了设置矩形大小的选项,这样做时矩形大小应该增加,但旧矩形的中心点应该是维护,使矩形内的内容不失焦

这是正确的做法吗

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)))

新矩形可以比旧矩形大或小。

计算正确;它可以只使用一个 integer division:
来简化 (又翻译成C#,因为源码是VB.Net

可以使用整数除法 (MSDN Docs),因为我们除以 2,这就像向下舍入。但是你应该在绘图时使用浮点值 (float),尤其是移动对象(值以度数表示,当然还有弧度):如果你不这样做,你的位置将会偏离很多。

objSmall.X = objBig.X + (objBig.Width - objSmall.Width) / 2;
objSmall.Y = objBig.Y + (objBig.Height - objSmall.Height) / 2;

(2):

objSmall.Location = new Point(objBig.X + (objBig.Width - objSmall.Width) / 2,
                              objBig.Y + (objBig.Height - objSmall.Height) / 2);

或者,使用较大对象的相对中心坐标:

Point BigRectCenter = new Point((objBig.Width / 2) + objBig.X, (objBig.Height / 2) + objBig.Y);

objSmall.Location = new Point(BigRectCenter.X - (objSmall.Width / 2),
                              BigRectCenter.Y - (objSmall.Height / 2));

不知道哪个Rectangle最大的时候也可以使用(2)方法
假设您知道参考矩形的 LocationSize 并且您让用户指定选择的新大小:

Rectangle OriginalRect = new Rectangle(30, 30, 120, 90);
Rectangle ResizedRect = new Rectangle(0, 0, 140, 140);

ResizedRect 有一个 Size(由用户定义),但它的 Location 目前未知。
新选择的矩形的 (ResizedRect) Location 可以计算为:

ResizedRect.Location = new Point(OriginalRect.X + (OriginalRect.Width - ResizedRect.Width) / 2,
                                 OriginalRect.Y + (OriginalRect.Height - ResizedRect.Height) / 2);

Original Selection (Green)                    Original Selection (Green)
    (20, 20, 120, 120)                           (30, 30, 120,  90)
 Resized Selection (Red)                       Resized Selection (Red) 
    ( 0,  0,  95,  86)                           ( 0,  0, 140, 140)

  Calculated Selection                          Calculated Selection
       Rectangle                                      Rectangle
    (32, 37,  95,  86)                           (20, 5, 140, 140)