您获得的线是三个不同贝塞尔曲线的并集 - 每组三个点对应一个曲线(每个“贝塞尔段”对应一个曲线)。
如果要得到单一平滑曲线,需要将9(或更多)个点作为一个点集(单个“贝塞尔段”)传递,而不是分成三个点一组。
编辑:显然,
BezierSegment
仅支持三个点,所以这就是为什么无法使用。即使
'PolyBezierSegment'也只提供一组贝塞尔段而不是单一平滑贝塞尔曲线...
因此,由于WPF没有提供有用的东西,我使用
这里的数学方法编写了一些代码。这是一个数值解决方案,但即使有足够的点使其看起来很平滑,它似乎也非常高效。
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, 0, 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, controlPoints, index, count - 1);
var P1 = GetBezierPoint(t, controlPoints, 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, 0),
new Point(350, 200),
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, 0));
((Grid)sender).Children.Add(p);
}
提供