1

I want to draw a curve according to a control points list. This is what I expected: enter image description here

Here are the control points: (0,90) (1,100) (-3,145) (10,150) (23,155) (73,108) (80,120) (86,131) (40,210) (50,220) (60,230) (148,185) (140,180) (131,175) (23,188) (0,190)

Here is my code:

public List<PointType> controlPoints;
public void render(Canvas canvas, Paint paint) {
        int size = controlPoints.size();
        if (size < 2) {
            return;
        }

        paint.setColor(this.color);
        paint.setStyle(this.style);

        Path curvePath = new Path();
        PointType firstPoint = null;
        PointType beginPoint = null;

        for (PointType point : controlPoints) {
            if (firstPoint == null) {
                firstPoint = point;
            } else if (beginPoint == null) {
                beginPoint = point;
            } else {
                curvePath.moveTo(firstPoint.x, firstPoint.y);
                curvePath.quadTo(beginPoint.x, beginPoint.y, point.x, point.y);
                firstPoint = beginPoint;
                beginPoint = point;
            }
        }

        canvas.drawPath(curvePath, paint);
    }

But the result is this:

enter image description here

What's wrong and How can I draw the correct curve?

Newton Zou
  • 558
  • 1
  • 5
  • 20
  • see http://stackoverflow.com/a/3813349/794088 – petey Dec 01 '16 at 16:07
  • You need to smooth the curve out, approximating it with lines will always look something like that. Look into Bezier splines as a first attempt – Gabe Sechan Dec 01 '16 at 16:07
  • https://github.com/autotrace maybe you can take something from this link.. it seems you need more points as it draw straight lines ... – Setar Dec 01 '16 at 16:35

1 Answers1

2

I've resolved the problem by below code:

public void render(Canvas canvas, Paint paint) {
        int size = controlPoints.size();
        if (size < 2) {
            return;
        }

        paint.setColor(this.color);
        paint.setStyle(this.style);

        Path curvePath = new Path();
        curvePath.moveTo(controlPoints.get(0).x, controlPoints.get(0).y);
        for (int idx = 1; idx < controlPoints.size(); idx += 3) {
            curvePath.cubicTo(controlPoints.get(idx).x,
                    controlPoints.get(idx).y, controlPoints.get(idx+1).x,
                    controlPoints.get(idx+1).y, controlPoints.get(idx+2).x,
                    controlPoints.get(idx+2).y);
        }

        canvas.drawPath(curvePath, paint);
    }
Newton Zou
  • 558
  • 1
  • 5
  • 20