1

I am trying to add points to the Path and drawing line between them, but nothing appear.

I have custom view:

public class BreakDownBar extends View {
private List<Point> points = new ArrayList<>();
private Path path = new Path();
private Paint p = new Paint();

public BreakDownBar(Context context) {
    super(context);
}

public BreakDownBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    p.setStrokeWidth(5);
    p.setStyle(Paint.Style.STROKE);
}

public void addPoint(Point point) {
    points.add(point);
    path.rewind();
    reDraw();
}

public void startPoint(Point point) {
    points.add(point);
}

private void reDraw() {
    Canvas canvas = new Canvas();
    path.moveTo(points.getFirst().getX(), points.getFirst().getY());
    for (int i = 1; i < points.size(); i++) {
        path.lineTo(points.get(i).getX(), points.get(i).getY());
    }


    canvas.drawPath(path, p);
    canvas.drawColor(Color.BLACK);
    draw(canvas);
    invalidate();
}

}

Point class:

public class Point {
private float x, y;

...getters and setters
}

While adding new points to the List I can see thought the expected result in the log, but nothing happen on the screen.

What I missed to make line appear on the screen?

1 Answer 1

4

You are using a bad logic to draw the line, if you call invalidate() you will request a call to draw() and this will reset your canvas.

Try with this version of your class:

public class BreakDownBar extends View {
    private List<Point> points = new ArrayList<>();
    private Path path = new Path();
    private Paint p = new Paint();

    public BreakDownBar(Context context) {
        super(context);
        p.setStrokeWidth(5);
        p.setStyle(Paint.Style.STROKE);
        p.setColor(Color.BLACK);
    }

    public void addPoint(Point point) {
        points.add(point);
        //this will request a call to draw(canvas) method
        invalidate();
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        //move to the first point in the list
        path.moveTo(points.get(0).getX(), points.get(0).getY());
        for (int i = 1; i < points.size(); i++) {
            path.lineTo(points.get(i).getX(), points.get(i).getY());
        }
        canvas.drawPath(path, p);
    }
}

Then in your code you can simply do

BreakDownBar bar = new BreakDownBar(context);
bar.addPoint(new Point(100f, 200f))
bar.addPoint(new Point(200f, 300f))
bar.addPoint(new Point(400f, 200f))

Let me know if this works for you.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.