问题描述
我有几点,我尝试使用下面的代码绘制贝塞尔曲线。
I have several points, and I try to draw Bezier curve using code below
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));
我的Bezier段看起来像这样
My Bezier segments look like this
- 1,2,3分 - 第一段
- 3,4,5分钟
- 7 .. ..
但是我得到了这个奇怪的曲线(这里是3个大节点和7个小椭圆)):
But I got this strange curve (here is 3 big (Nodes) and 7 small ellipse (is my points)):
推荐答案
你得到的线是三个不同贝塞尔曲线的联合 - 每组三个点。 (每个Bezier段一个?)
The line you're getting is the union of three distinct Bezier curves - one for each group of three points. (One for each "Bezier segment"?)
如果你想要一个平滑的曲线,你需要传递你的9(或更多) (单个Bezier段?),而不是三点组。
If you want a single smooth curve, you need to pass your 9 (or more) points as a single collection of points (single "Bezier segment"?), not as groups of three points.
编辑:显然仅支持三点,所以难怪这不工作。即使仅提供了一组贝塞尔曲线段,而不是单个平滑的Bezier ...
Apparently BezierSegment
only supports three points, so no wonder this doesn't work. Even 'PolyBezierSegment' just gives a collection of Bezier segments rather than a single smooth Bezier...
因为WPF没有给你任何有用的东西,我使用数学。这是一个数字解决方案,但它似乎是非常性能,即使有足够的点,看起来不错,顺利:
So since WPF doesn't give you anything useful, I knocked something together using the maths here. It's a numeric solution, but it seems to be pretty performant even with enough points to look nice and smooth:
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);
}
提供
这篇关于如何绘制贝塞尔曲线几点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!