C# · 12月 28, 2021

c# – 如何用几点绘制贝塞尔曲线?

我有几点,我试图用下面的代码绘制贝塞尔曲线 Pathfigure pf = new Pathfigure(points.From,ps,false); //ps – list of Bezier segments PathfigureCollection pfc = new PathfigureCollection(); pfc.Add(pf); var pge = new PathGeometry(); pge.figures = pfc; Path p = new Path(); p.Data = pge; p.stroke = new SolidColorBrush(Color.FromRgb(244,111,011));

我的贝塞尔区段看起来像这样

> 1,2,3分 – 第一段
> 3,4,5分 – 秒
> 5,6,7 .. ..

但是我得到了这个奇怪的曲线(这里有3个大节点)和7个小椭圆(是我的分数)):

解决方法 你得到的线是三个不同的贝塞尔曲线的联合 – 每三组一个. (每个“Bezier segment”一个?)

如果你想要一个单一的平滑曲线,你需要把你的9点(或更多)点作为一个单一的点集合(单个“Bezier segment”?),而不是三分组.

编辑:显然BezierSegment只支持三点,所以难怪这不行.即使‘PolyBezierSegment’只是给出一个Bezier段的集合,而不是一个平滑的Bezier …

所以,因为WPF并没有给你任何有用的东西,所以我用数学here一起敲了一下.这是一个数字解决方案,但是即使有足够的观点看起来很好又顺利,它似乎是很好的表现:

PolyLineSegment GetBezierApproximation(Point[] controlPoints,int outputSegmentCount){ Point[] points = new Point[outputSegmentCount + 1]; for (int i = 0; i <= outputSegmentCount; i++) { double t = (double)i / outputSegmentCount; points[i] = GetBezierPoint(t,controlPoints,controlPoints.Length); } return new PolyLineSegment(points,true);}Point GetBezierPoint(double t,Point[] controlPoints,int index,int count){ if (count == 1) return controlPoints[index]; var P0 = GetBezierPoint(t,index,count – 1); var P1 = GetBezierPoint(t,index + 1,count – 1); return new Point((1 – t) * P0.X + t * P1.X,(1 – t) * P0.Y + t * P1.Y);}

使用这个,

private void Grid_Loaded(object sender,RoutedEventArgs e){ Point[] points = new[] { new Point(0,200),new Point(0,0),new Point(300,new Point(350,new Point(400,0) }; var b = GetBezierApproximation(points,256); Pathfigure pf = new Pathfigure(b.Points[0],new[] { b },false); PathfigureCollection pfc = new PathfigureCollection(); pfc.Add(pf); var pge = new PathGeometry(); pge.figures = pfc; Path p = new Path(); p.Data = pge; p.stroke = new SolidColorBrush(Color.FromRgb(255,0)); ((Grid)sender).Children.Add(p);}