Android系统。帆布。 Dinamically添加路径点

时间:2017-09-13 12:28:15

标签: android canvas path drawing

我正在尝试将点添加到Path并在它们之间绘制线条,但没有任何内容出现。

我有自定义视图:

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();
}

}

class

public class Point {
private float x, y;

...getters and setters
}

List添加新点时,我可以看到日志中的预期结果,但屏幕上没有任何结果。

我错过了哪些线条出现在屏幕上?

1 个答案:

答案 0 :(得分:1)

您使用错误的逻辑画线,如果您拨打invalidate(),则会要求拨打draw(),这将重置您的画布。

尝试使用此版本的课程:

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);
    }
}

然后在你的代码中你可以做到

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

请告诉我这是否适合您。