如何合并两个相互重叠的动态创建对象?

时间:2009-12-11 10:38:51

标签: wpf geometry

请在下面找到我的代码。我尝试了这个,但没有成功。有什么帮助吗?

Path e1 = new Path();
Path e2 = new Path();

e1.Data = new EllipseGeometry(new Rect(new Size(100, 100)));
e1.RenderTransform = new TranslateTransform(100, 100);
e1.Fill = Brushes.Transparent;
e1.Stroke = Brushes.Black;

e2.Data = new EllipseGeometry(new Rect(new Size(120, 120)));
e2.RenderTransform = new TranslateTransform(140, 140);
e2.Fill = Brushes.Transparent;
e2.Stroke = Brushes.Black;

Path p = new Path();

CombinedGeometry c1 = new CombinedGeometry();
Geometry g1 = e1.Data.Clone();
Geometry g2 = e2.Data.Clone();
c1.GeometryCombineMode = GeometryCombineMode.Union;

p.Stroke = Brushes.Black;
p.StrokeThickness = 1;
p.Data = c1;

canvasMain.Children.Add(p);

问候/ subho100

2 个答案:

答案 0 :(得分:2)

你犯了两个错误:

第一个假设转换会改变几何体的位置 - 我的测试显示它们被忽略所以我使用了另一个Rect构造函数,它带有Point位置。

第二个是Anurag纠正的一个更基本的错误 - 你实际上并没有将几何体放入CombinedGeometry。我使用构造函数以不同的方式解决了它,如下所示。

Path e1 = new Path();
Path e2 = new Path();

e1.Data = new EllipseGeometry(new Rect(new Point(100,100), new Size(100, 100)));
e1.Fill = Brushes.Transparent;
e1.Stroke = Brushes.Black;

e2.Data = new EllipseGeometry(new Rect(new Point(140, 140), new Size(120, 120)));
e2.Fill = Brushes.Transparent;
e2.Stroke = Brushes.Black;

Path p = new Path();

CombinedGeometry c1 = new CombinedGeometry(GeometryCombineMode.Union, e1.Data, e2.Data);

p.Stroke = Brushes.Black;
p.StrokeThickness = 1;
p.Data = c1;

canvasMain.Children.Add(p);

答案 1 :(得分:0)

在代码中的最后一行之前添加此内容

c1.Geometry1 = g1;
c1.Geometry2 = g2;

希望这会有所帮助!!