Reputation: 127
I want to draw some lines in android. I use SampleView class and it's onDraw, like this :
private class SampleView extends View {
public SampleView(Context context) {
super(context);
setFocusable(true);
}
@Override
protected void onDraw(Canvas canvas) {
p.setAntiAlias(true);
p.setColor(Color.RED);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(5);
canvas.drawLine(x0, y0, x1, y1, p);
}
}
my x0,x1,y0,y1 changes in every time that I call sv.invalidate(). every time that it is drawing new line, my previous line is cleared ... but I want to keep all lines. How can I do this?
Upvotes: 1
Views: 122
Reputation: 4338
You should keep track of the lines within a Path component. Add to the path when you have a new line to draw. Then you can draw the path within the onDraw() or clear the path when you need to for whatever reason.
One example might be something like this:
public void onDraw(Canvas canvas)
{
Path path = new Path();
boolean isFirstPoint = true;
for(Point point : points)
{
if(isFirstPoint)
{
isFirstPoint = false;
path.moveTo(point.x, point.y);
}
else
{
path.lineTo(point.x, point.y);
}
}
canvas.drawPath(path, paint);
}
But, of course, there are many ways to accomplish this. The onDraw method is meant to update frequently and draws what you tell it, you have to keep state.
Upvotes: 1