我正在创建一个基本的绘图应用程序。以下函数用于绘制线。
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;
}
}
和 drawLine()函数是
private void drawLine(float x2,float y2){
mPath.lineTo(x2,y2);
invalidate();
Log.e("Canvas","Line Drawn");
}
我的 onDraw()功能
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");
}
我的问题是该线是从屏幕的左上角绘制的。我相信它是(0,0)。我使用相同的逻辑绘制圆形和矩形,两者都工作正常。 我的逻辑是否有任何错误。? 我怎样才能解决这个问题..? 提前致谢
答案 0 :(得分:2)
这很容易。 你应该打电话
path.moveTo(firstPoint_X, firstPoint_y);
在图纸的第一步。
(在您调用mPath = new Path();)的每一行之后
如果你不打电话
在创建Path类的新实例后的path.moveTo
方法,默认情况下它从屏幕的位置(0,0)开始绘制