draw line- Android
I want to draw a line on screen using touch listener, but when i try to draw line again it erases the previous line. I am using this code:-
I am unable to 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(color开发者_如何学运维draw);
canvas.drawLine(x1, y1, x2, y2, p);
invalidate();
}
}
I'm pretty sure that invalidate() wipes the canvas, so you have to keep a collection of lines that 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();
}
}
精彩评论