Reputation: 73
I have created canvas in one Android application where you can draw lines following your finger. Everything in that point works, but I would like to start new line from last line's endpoint coordinates.
I thought that I can just put last line end coordinates to action down event for new line, but that way there is no coordinates for first line or it wouldn't know from where to start
Currently my code is like that and this makes just lines, not connected. Is this somehow even possible ?
protected float mStartX;
protected float mStartY;
protected float mx;
protected float my;
private void drawLine(android.graphics.Canvas canvas) {
float dx = Math.abs(mx - mStartX);
float dy = Math.abs(my - mStartY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
canvas.drawLine(mStartX, mStartY, mx, my, mPaint);
}
}
private void lineDrawEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isDrawing = true;
mStartX = mx;
mStartY = my;
invalidate();
break;
case MotionEvent.ACTION_MOVE:
invalidate();
break;
case MotionEvent.ACTION_UP:
isDrawing = false;
mCanvas.drawLine(mStartX, mStartY, mx, my, mPaintFinal);
invalidate();
break;
}
}
Upvotes: 1
Views: 117
Reputation: 10252
Yes possible just store the end point of the last line to use as the start of the next line as you said yourself.
What you need to do is change the behaviour of ACTION_DOWN
if you already have a start point
Something like:-
protected float mStartX;
protected float mStartY;
protected float mx;
protected float my;
private void drawLine(android.graphics.Canvas canvas) {
float dx = Math.abs(mx - mStartX);
float dy = Math.abs(my - mStartY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
canvas.drawLine(mStartX, mStartY, mx, my, mPaint);
}
}
private void lineDrawEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isDrawing = true;
// If this is the first line then the start values will be
// uninitialised, so only use them for the start of the first line
// Otherwise they will be set by the previous UP event
if (mStartX == null && mStartY == null) {
mStartX = mx;
mStartY = my;
}
invalidate();
break;
case MotionEvent.ACTION_MOVE:
invalidate();
break;
case MotionEvent.ACTION_UP:
isDrawing = false;
mCanvas.drawLine(mStartX, mStartY, mx, my, mPaintFinal);
// Set the Start point of the next line to end of current
mStartX = mx;
mStartY = my;
invalidate();
break;
}
}
You might want to also add each point to List of Pair Object as well, so you can do something with the lines afterwards.
Upvotes: 2