Draw a line - Android

I want to draw a line on the screen using the touch listener, but when I try to draw a line again, it erases the previous line. I am using this code: -

I can not find a solution to the problem.

public class Drawer extends View
{
    public Drawer(Context context)
    {
        super(context);
    }

    protected void onDraw(Canvas canvas)
    {
        Paint p = new Paint();
        p.setColor(colordraw);
        canvas.drawLine(x1, y1, x2, y2, p);
        invalidate();
    }
}
+3
source share
1 answer

I am sure invalidate () erases the canvas, so you need to save the set of lines you want to draw. Then you need to draw ALL of them EVERY time before calling invalidate ().

private class Line {

    public Line(int x1, int y1, int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }
    ...    
}

public class Drawer extends View
{  
    ArrayList<Line> lines;
    public Drawer(Context context)
    {
        super(context);
        lines = new ArrayList<Line>();
    }

    public void addLine(int x1, int y1, int x2, int y2) {
        Line newLine = new Line(x1, y1, x2, y2);
        lines.add(newLine);
    }

    protected void onDraw(Canvas canvas)
    {
        Paint p = new Paint();
        p.setColor(colordraw);
        for (Line myLine : lines) {
            canvas.drawLine(myLine.getX1(), myLine.getY1(), myLine.getX2(), myLine.getY2(), p);
        }
        invalidate();
    }
}
+2
source

All Articles