Reputation: 94
I am creating a basic drawing application. The following functions are used to draw the line.
public void touchEventLine(MotionEvent event){
Log.e("Canvas","Line Specific Event");
float x = event.getX();
float y = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.e("Canvas","Line Specific Event: Action Down");
startX=x;
startY=y;
mPath.moveTo(startX,startY);
Log.e("Canvas","Line Specific Event: Moved to X:"+startX+" Y:"+startY);
mX=x;
mY=y;
invalidate();
break;
case MotionEvent.ACTION_MOVE:
Log.e("Canvas","Line Specific Event: Action Move");
endX=x;
endY=y;
drawLine(endX,endY);
Log.e("Canvas","Line Specific Event: Drawing From X:"+startX+" Y:"+startY+" to X:"+endX+" Y:"+endY);
paths.add(mPath);
colorsMap.put(mPath,selectedColor);
mPath = new Path();
isDrawing++;
invalidate();
if(isDrawing>1) {
paths.remove(paths.size() - 2);
isDrawing--;
}
break;
case MotionEvent.ACTION_UP:
Log.e("Canvas","Line Specific Event: Action Up");
endX=x;
endY=y;
drawLine(endX,endY);
paths.add(mPath);
colorsMap.put(mPath,selectedColor);
mPath = new Path();
paths.remove(paths.size() - 2);
invalidate();
isDrawing=0;
break;
}
}
and the drawLine() function is
private void drawLine(float x2,float y2){
mPath.lineTo(x2,y2);
invalidate();
Log.e("Canvas","Line Drawn");
}
and my onDraw() function is
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mBitmap, 0, 0, canvasPaint);
canvas.drawPath(mPath,drawPaint);
for (Path p : paths) {
int curColor= colorsMap.get(p);
drawPaint.setColor(curColor);
canvas.drawPath(p, drawPaint);
}
Log.e("Canvas","OnDraw() Called");
}
My problem is that the line is drawing from top left corner of screen. I believe it is (0,0). I used the same logic for drawing circle and rectangle and both working fine. Is there any mistake in my logic.? How can I fix this..? Thanks in advance
Upvotes: 0
Views: 894
Reputation: 514
It's easy. you should call
path.moveTo(firstPoint_X, firstPoint_y);
at the first of the drawing.
(after each line that you call mPath = new Path(); )
if you don't call
path.moveTo
method after you make a new instance of Path class,by default it start drawing from position(0,0) of screen
Upvotes: 2