4

我在此视图中创建了一个视图,我想在获取用户触摸屏幕的像素后显示该框,但 onDraw 方法不会将画布更新为触摸屏幕。你们能帮帮我吗?

     public class PlayView extends View
{
float width,height;
float touchatX, touchatY;
boolean isanyBox;

public void init()
{
    isanyBox = false;

}


    @Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) 
 {
   // TODO Auto-generated method stub

   width = w/6f;
   height = h/6f;

    super.onSizeChanged(w, h, oldw, oldh);
}

public PlayView(Context context)
   {
       super(context);
       setFocusable(true);
       setFocusableInTouchMode(true);
       init();
   }


     @Override
    public boolean onTouchEvent(MotionEvent event) 
  {
    // TODO Auto-generated method stub

   isanyBox = true;
   touchatX = (event.getX()/6)*6;
   touchatY = (event.getY()/6)*6;

    return super.onTouchEvent(event);
}

   public void onDraw(Canvas canvas)
 {
   Paint lineColor = new Paint();
   lineColor.setColor(Color.BLACK);

   //Box property
   Paint boxColor = new Paint();
   boxColor.setColor(Color.BLUE);

   //Draw horizontal lines
   for(int i=0; i<6; i++)
   {
      canvas.drawLine(0, i*height, getWidth(), i*height, lineColor);
   }

   //Draw vertical lines
   for(int j=0; j<6; j++)
   {
       canvas.drawLine(j*width, 0, j*width, getHeight(), lineColor);
   }

  // if(isanyBox)
  // {
   canvas.drawRect(touchatX+1, touchatY+2, touchatX+width-1, touchatY+height-2, boxColor);
  // }


  }
 }
4

1 回答 1

3

把无效();进入 onTouchEvent,

@Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub

        isanyBox = true;
        touchatX = (event.getX() / 6) * 6;
        touchatY = (event.getY() / 6) * 6;
        invalidate();

        return super.onTouchEvent(event);
    }
于 2012-12-25T08:42:42.007 回答