I am trying to create a rectangle, but this is what happens when I move from starting coordinates towards the end coordinates
, actually I want to show the progress when the user moves from one point to other as well.This is what I would like to have. .
Code:-
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
//v.invalidate();
break;
case MotionEvent.ACTION_MOVE:
upx = event.getX();
upy = event.getY();
canvas.drawRect(downx, downy, upx, upy, paint);
}
choosenImageView.invalidate();
break;
case MotionEvent.ACTION_UP:
upx = event.getX();
upy = event.getY();
canvas.drawRect(downx, downy, upx, upy, paint);
}
}
// v.invalidate();
break;
}
return true;
}
Edit What I would like to do is to show the progress i.e. as the user moves his finger, shape should be drawn.
Suggestions/Samples/links anything will be appreciated.
You are directly updating the canvas in the onTouch()
event without clearing it first. This is not the supposed way of drawing something in a View (assuming this is what you want).
Instead you are supposed to store the begin and current coordinates of the rectangle and use them in the onDraw()
event to draw the actual rectangle (after Adnroid cleared the invalidated part of the Canvas for you). Android will issue this event if the canvas needs to be redrawn, so you need to tell that this is required in the onTouch()
event, by using the invalidate()
method:
class myView extends View { // or some other View-based class
boolean drawRectangle = false;
PointF beginCoordinate;
PointF endCoordinate;
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawRectangle = true; // Start drawing the rectangle
beginCoordinate.x = event.getX();
beginCoordinate.y = event.getY();
endCoordinate.x = event.getX();
endCoordinate.y = event.getY();
invalidate(); // Tell View that the canvas needs to be redrawn
break;
case MotionEvent.ACTION_MOVE:
endCoordinate.x = event.getX();
endCoordinate.y = event.getY();
invalidate(); // Tell View that the canvas needs to be redrawn
break;
case MotionEvent.ACTION_UP:
// Do something with the beginCoordinate and endCoordinate, like creating the 'final' object
drawRectangle = false; // Stop drawing the rectangle
invalidate(); // Tell View that the canvas needs to be redrawn
break;
}
return true;
}
protected void onDraw(Canvas canvas) {
if(drawRectangle) {
// Note: I assume you have the paint object defined in your class
canvas.drawRect(beginCoordinate.x, beginCoordinate.y, endCoordinate.x, endCoordinate.y, paint);
}
}
}
Do you clean the canvas between two rectangle ? Add a function like this one :
void clearCanvas()
{
canvas.drawRect(0,0, width, height, paint);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With