我是Android开发中的新手,我在这里有一个问题,因为我还没有在Stackoverflow上找到任何答案。
我编写了一个简单的代码,让用户在屏幕上用一根手指绘制一个边界框(从左上角到右下角)。
DrawView类看起来像这样:
public class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
}
public Point startPoint = new Point();
public Point endPoint = new Point();
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.RED);
paint.setStrokeWidth(3);
paint.setStyle(Paint.Style.STROKE);
canvas.drawRect(startPoint.x,startPoint.y,endPoint.x,endPoint.y,paint);
}}
并且mainActivity看起来像这样:
public class MainActivity extends AppCompatActivity {
DrawView drawView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
drawView.startPoint.set(0,0);
drawView.endPoint.set(0,0);
setContentView(drawView);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int eventAction = event.getAction();
// you may need the x/y location
int x = (int)event.getX();
int y = (int)event.getY();
// put your code in here to handle the event
switch (eventAction) {
case MotionEvent.ACTION_DOWN:
drawView.startPoint.set(x,y);
break;
case MotionEvent.ACTION_UP:
drawView.endPoint.set(x,y);
drawView.invalidate();
break;
case MotionEvent.ACTION_MOVE:
drawView.endPoint.set(x,y);
drawView.invalidate();
break;
}
// tell the View that we handled the event
return true;
}}
结果是我的手指点和屏幕上的真实绘图点之间有一个很大的距离,如下所示:
蓝线是我的手指,红色边框是屏幕上的真实绘图。有谁知道这个的原因?非常感谢!
答案 0 :(得分:0)
活动&子视图没有相同的坐标原点。我做了一些更正:
public class MainActivity extends AppCompatActivity implements View.OnTouchListener{
DrawView drawView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
drawView.startPoint.set(0, 0);
drawView.endPoint.set(0, 0);
setContentView(drawView);
drawView.setOnTouchListener(this);
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int eventAction = motionEvent.getAction();
// you may need the x/y location
int x = (int) motionEvent.getX();
int y = (int) motionEvent.getY();
// put your code in here to handle the event
switch (eventAction) {
case MotionEvent.ACTION_DOWN:
drawView.startPoint.set(x, y);
break;
case MotionEvent.ACTION_UP:
drawView.endPoint.set(x, y);
drawView.invalidate();
break;
case MotionEvent.ACTION_MOVE:
drawView.endPoint.set(x, y);
drawView.invalidate();
break;
}
// tell the View that we handled the event
return true;
}
}