我想使用触摸侦听器在屏幕上绘制一条线,但是当我尝试再次绘制线时,它会擦除前一行。我正在使用此代码: -
我无法找到解决问题的方法。
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();
}
}
答案 0 :(得分: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();
}
}