画线 - Android

3

我希望能够使用触摸监听器在屏幕上绘制一条直线,但是当我尝试再次绘制直线时,它会擦除先前的直线。我正在使用以下代码:

我无法找到解决这个问题的方法。

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

已经多次发布:http://stackoverflow.com/questions/6372556/android-draw-line - Matthieu
1个回答

2

我相信invalidate()会清除画布,所以你需要保留想要绘制的所有线条的集合。然后在调用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();
    }
}

我更新了我的答案,包括示例代码,展示了基本思路。 - Travis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接