在画布Android中触摸事件后随机位置绘制矩形

时间:2014-10-19 05:22:11

标签: java android canvas

我试图在Canvas中的随机位置绘制一个矩形(不应超过画布尺寸),如果用户触摸该形状,它应该在另一个随机位置绘制。我已设法绘制矩形,但需要Touch Event的帮助,然后在随机位置绘制它。

public class DrawView extends View {
    Paint paint = new Paint();

    public DrawView(Context context) {
        super(context);            
    }

    @Override
    public void onDraw(Canvas canvas) {
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(3);
        canvas.drawRect(30, 30, 80, 80, paint);
        paint.setStrokeWidth(0);
        paint.setColor(Color.CYAN);
        canvas.drawRect(33, 60, 77, 77, paint );
        paint.setColor(Color.YELLOW);
        canvas.drawRect(33, 33, 77, 60, paint );

    }

}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

你可以这样做,如下所示:

例如

     public class DrawView extends View {

     // here you define hashmap for user touch points

    Paint paint = new Paint();

    public DrawView(Context context) {
        super(context);            
    }

    @Override
    public void onDraw(Canvas canvas) {
       yourRandomFunction(-99,-99);


    }
 public void yourRandomFunction(float x , float y ){
    //for first time user touch 
    // if -99 && -99 { 
    //Calculate random points here.

     paint.setColor(Color.BLACK);
        paint.setStrokeWidth(3);
        canvas.drawRect(30, 30, 80, 80, paint);
        paint.setStrokeWidth(0);
        paint.setColor(Color.CYAN);
        canvas.drawRect(33, 60, 77, 77, paint );
        paint.setColor(Color.YELLOW);
        canvas.drawRect(33, 33, 77, 60, paint );
        // add points to hashmap
    }
    //else check in hashmap if exist then {
      //Calculate random points here.
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(3);
        canvas.drawRect(30, 30, 80, 80, paint);
        paint.setStrokeWidth(0);
        paint.setColor(Color.CYAN);
        canvas.drawRect(33, 60, 77, 77, paint );
        paint.setColor(Color.YELLOW);
        canvas.drawRect(33, 33, 77, 60, paint );
        // add point to hashmap
     } 

 }
 @Override
 public boolean onTouchEvent(MotionEvent event) {
  float eventX = event.getX();
   float eventY = event.getY();

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
  //check points in hashmap 

  return true;
case MotionEvent.ACTION_MOVE:

  break;
case MotionEvent.ACTION_UP:
  // nothing to do
  yourRandomFuncntion(eventX,eventY);
  break;
default:
  return false;
}

// Schedules a repaint.
invalidate();
return true;
  }
}