加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 03:52:44 所属栏目:百科 来源:网络整理
导读:我有几点,我试图用下面的代码绘制贝塞尔曲线 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 =
我有几点,我试图用下面的代码绘制贝塞尔曲线
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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读