I need to draw a rectangle on the canvas with points from ontouch events. i got the rectangle shape working but when i draw another rectangle the previous rectangle disappears. I think i need to store the rectangle points in some array. please suggest me some ideas.
So far my code is as follows.
first in ontouch method in view class
private void onTouchEvent(MotionEvent event) {
xTouchCoordinate = event.getX();
yTouchCoordinate = event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
isActionUp = false;
pushState ();
startX = event.getX();
startY = event.getY();
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
isActionUp = true;
}
else if (event.getAction() == MotionEvent.ACTION_MOVE){
isActionUp = false;
if(mTouchMode == TouchModes.RECTANGLE )
{
updateRectPath(startX,startY , xTouchCoordinate , yTouchCoordinate);
}
}
}
and onDraw method is
protected void onDraw(Canvas canvas) {
ImageObject.setInteractiveMode(true);
int sc = canvas.save();
canvas.drawColor(Color.BLACK);
canvas.scale(mCanvasScale, mCanvasScale);
canvas.translate(mCanvasOffset.x, mCanvasOffset.y);
canvas.clipRect(mCanvasLimits);
canvas.drawColor(Color.WHITE);
if (currentState.drawGrid)
drawGridLines (canvas);
drawImages (canvas, true);
drawLines (canvas);
drawRectangles(canvas);
drawCircles(canvas);
drawOvals(canvas);
drawImages (canvas, false);
}
DrawRectangles method
private void drawRectangles(Canvas canvas) {
try
{
if(path!=null)
{
if(mTouchMode == TouchModes.RECTANGLE)
{
finishPath(canvas);
}
}
}catch(Exception e)
{
}
}
finishpath method
void finishPath(Canvas canvas) {
if(mTouchMode == TouchModes.RECTANGLE)
{
paint = new Paint();
paint.setAntiAlias(true);
paint.setDither(true);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(currentState.currentColor);
paint.setFlags(Paint.DITHER_FLAG | Paint.ANTI_ALIAS_FLAG);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(currentStrokeWidth);
canvas.drawPath(path, paint);
}
}
void updateRectPath(float x1, float y1, float x2, float y2) {
path.rewind();
x1 = x1 - mCanvasOffset.x;
y1 = y1 - mCanvasOffset.y;
x2 = x2 - mCanvasOffset.x;
y2 = y2 - mCanvasOffset.y;
translate(x1, y1);
Log.d ("x1 is "+x1, "y1 is "+y1);
if (x1 < x2 && y1 > y2) {
path.addRect(x1, y2, x2, y1, Path.Direction.CW);
}
if (x1 < x2 && y1 < y2) {
path.addRect(x1, y1, x2, y2, Path.Direction.CW);
}
if (x1 > x2 && y1 > y2) {
path.addRect(x2, y2, x1, y1, Path.Direction.CW);
}
if (x1 > x2 && y1 < y2) {
path.addRect(x2, y1, x1, y2, Path.Direction.CW);
}
}