赞
踩
C# 在矩形内获取一个指定大小的矩形(两个矩形的中心点是重合的)
- using System.Drawing;
-
- public class RectangleUtils
- {
- public static Rectangle GetInnerRectangle(Rectangle outerRectangle, Size innerSize)
- {
- // 计算内部矩形的左上角坐标
- int left = outerRectangle.Left + (outerRectangle.Width - innerSize.Width) / 2;
- int top = outerRectangle.Top + (outerRectangle.Height - innerSize.Height) / 2;
-
- // 返回内部矩形
- return new Rectangle(left, top, innerSize.Width, innerSize.Height);
- }
-
- public static void Main()
- {
- // 定义外部矩形
- Rectangle outerRectangle = new Rectangle(100, 100, 400, 300);
-
- // 定义内部矩形的大小
- Size innerSize = new Size(200, 150);
-
- // 获取内部矩形
- Rectangle innerRectangle = GetInnerRectangle(outerRectangle, innerSize);
-
- // 输出内部矩形的坐标和大小
- Console.WriteLine("内部矩形的坐标:({0}, {1})", innerRectangle.Left, innerRectangle.Top);
- Console.WriteLine("内部矩形的大小:{0}x{1}", innerRectangle.Width, innerRectangle.Height);
- }
- }

在上面的代码中,GetInnerRectangle 方法接受一个外部矩形和一个内部矩形的大小作为参数。它计算内部矩形的左上角坐标,并返回一个新的 Rectangle 对象。
在 Main 方法中,我们定义了一个外部矩形和一个内部矩形的大小。然后,调用 GetInnerRectangle 方法获取内部矩形,并输出其坐标和大小。
请注意,上述代码假设内部矩形的大小不会超出外部矩形的范围。如果内部矩形的大小超过了外部矩形的大小,需要进行适当的边界检查和处理。
- using System.Drawing; // 如果是Windows Forms或GDI+
-
- // 假设已有一个大的Rectangle对象rectParent和你想要创建的小矩形尺寸sizeChild
- Rectangle rectParent;
- Size sizeChild;
-
- // 计算小矩形中心点在大矩形内的坐标,保证两者中心点重合
- Point centerOfBothRects = new Point(
- rectParent.X + rectParent.Width / 2,
- rectParent.Y + rectParent.Height / 2
- );
-
- // 根据中心点坐标和小矩形尺寸创建新的小矩形
- Rectangle rectChild = new Rectangle(
- centerOfBothRects.X - sizeChild.Width / 2,
- centerOfBothRects.Y - sizeChild.Height / 2,
- sizeChild.Width,
- sizeChild.Height
- );
-
- // 检查小矩形是否完全在大矩形内(由于已经确保中心点重合,通常不需要此步骤)
- if (rectParent.Contains(rectChild))
- {
- // 小矩形成功在大矩形内生成并且中心点与大矩形中心点重合
- }
- else
- {
- // 在这种情况下理论上不会发生,除非sizeChild超出rectParent范围
- // 可能需要调整大小以适应大矩形
- }

这段代码首先计算了大矩形的中心点坐标,并假设这个坐标就是小矩形的中心点。然后根据小矩形的尺寸从中心点向两边扩展来创建小矩形,确保两个矩形的中心点重合。如果事先知道小矩形尺寸始终小于等于大矩形尺寸,则无需检查rectParent.Contains(rectChild)。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。