我试图在canvas
上画一个正方形,但只运行MotionEvent.ACTION_DOWN
,然后listener
停止。
这个想法是当用户触摸屏幕时它获得x1和y1位置,每次onTouch
被触发时,它必须将rect frim x1 y1绘制到当前位置,最后保存最后一个位置一旦用户离开屏幕,x2 y2。
我的代码如下所示:
surfaceView.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
holder = surfaceView.getHolder();
canvas = holder.lockCanvas();
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
x1=event.getX();
y1=event.getY();
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
x2=event.getX();
y2=event.getY();
}
canvas.drawRect(x1, y1, event.getX(), event.getY(), paint);
holder.unlockCanvasAndPost(canvas);
return true;
}
});
任何人都可以举个例子。
答案 0 :(得分:1)
ACTION_UP从上面的代码触发。尝试下面的代码,您将看到日志。
我认为您的问题可能与您获得的观点有关。我不知道你是如何定义x1,y1,x2,y2但是当声明超出范围时它们必须是最终的。试试这个。
final SurfaceView s = (SurfaceView) findViewById(R.id.surface);
final RectF rect = new RectF();
s.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
SurfaceHolder holder = s.getHolder();
Canvas canvas = holder.lockCanvas();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
Log.d("action", "down");
rect.left = event.getX();
rect.top = event.getY();
}
if(event.getAction() == MotionEvent.ACTION_UP){
Log.d("action", "up");
rect.right = event.getX();
rect.bottom = event.getY();
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawRect(rect, paint);
}
holder.unlockCanvasAndPost(canvas);
return true;
}
});
答案 1 :(得分:0)
尝试使用它。
surfaceView.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
x1=event.getX();
y1=event.getY();
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
x2=event.getX();
y2=event.getY();
holder = surfaceView.getHolder();
canvas = holder.lockCanvas();
canvas.drawRect(x1, y1, x2, y2, paint);
holder.unlockCanvasAndPost(canvas);
}
return true;
}
});
如果你移动手指,它会在你做的每一个动作中呼叫听众。 所以这段代码
holder = surfaceView.getHolder();
canvas = holder.lockCanvas();
和此代码
canvas.drawRect(x1, y1, event.getX(), event.getY(), paint);
holder.unlockCanvasAndPost(canvas);
将被执行,也许这就是它停止的原因。
所以我将drawRect
置于MotionEvent.ACTION_UP
条件中,因此drawRect
将执行一次。