示例代码1,求非重合部分:
使用GraphicsPath获取到非重合的路径,然后使用FillPath填充非重合部分Brush颜色。
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.Drawing.Imaging;
-
- public class Program
- {
- public static void Main()
- {
- // 假设你已经有了两个Rectangle,rect1和rect2
- Rectangle rect1 = new Rectangle(new Point(10, 10), new Size(50, 50));
- Rectangle rect2 = new Rectangle(new Point(20, 20), new Size(40, 40));
-
- // 创建两个 GraphicsPath 对象
- GraphicsPath path1 = new GraphicsPath();
- GraphicsPath path2 = new GraphicsPath();
-
- // 向第一个 GraphicsPath 对象添加较大矩形
- path1.AddRectangle(rect1);
-
- // 向第二个 GraphicsPath 对象添加较小矩形
- path2.AddRectangle(rect2);
-
- // 创建两个 Region 对象,一个用于第一个 GraphicsPath,一个用于第二个 GraphicsPath
- Region region1 = new Region(path1);
- Region region2 = new Region(path2);
-
- // 使用 Exclude 方法计算两个 Region 对象的差集
- region1.Exclude(region2);
-
- // 创建一个Brush对象来填充非重叠部分的颜色
- SolidBrush m_Brush = new SolidBrush(Color.Red);
-
- // 使用Graphics.FillPath方法填充非重叠部分
- using (Graphics g = this.CreateGraphics())
- {
- g.FillRegion(m_Brush, region1);
- }
-
- }
- }
示例代码2,求重合部分::
使用GraphicsPath获取到重合的路径,然后使用FillPath填充重合部分Brush颜色。
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.Drawing.Imaging;
-
- public class Program
- {
- public static void Main()
- {
- // 假设你已经有了两个Rectangle,rect1和rect2
- Rectangle rect1 = new Rectangle(new Point(10, 10), new Size(50, 50));
- Rectangle rect2 = new Rectangle(new Point(20, 20), new Size(40, 40));
-
- // 创建两个 GraphicsPath 对象
- GraphicsPath path1 = new GraphicsPath();
- GraphicsPath path2 = new GraphicsPath();
-
- // 向第一个 GraphicsPath 对象添加较大矩形
- path1.AddRectangle(rect1);
-
- // 向第二个 GraphicsPath 对象添加较小矩形
- path2.AddRectangle(rect2);
-
- // 创建两个 Region 对象,一个用于第一个 GraphicsPath,一个用于第二个 GraphicsPath
- Region region1 = new Region(path1);
- Region region2 = new Region(path2);
-
- // 使用 Intersect 方法计算两个 Region 对象的差集
- region1.Intersect(region2);
-
- // 创建一个Brush对象来填充非重叠部分的颜色
- SolidBrush m_Brush = new SolidBrush(Color.Red);
-
- // 使用Graphics.FillPath方法填充非重叠部分
- using (Graphics g = this.CreateGraphics())
- {
- g.FillRegion(m_Brush, region1);
- }
-
- }
- }
C# 在矩形内获取一个指定大小的矩形(两个矩形的中心点是重合的)-CSDN博客