当前位置: 代码迷 >> Android >> android的拖拽有关问题-onTouchEvent事件
  详细解决方案

android的拖拽有关问题-onTouchEvent事件

热度:15   发布时间:2016-05-01 14:10:01.0
android的拖拽问题--onTouchEvent事件

要实现图片的拖拽 主要是通过onTouchEven计算好坐标事件 然后进行重绘。下面的程序是别人的,重新加载 了一次

?img = BitmapFactory.decodeResource(context.getResources(), drawable); 加载一个图片在案例中专门做了一个类 进行设置。

加载图片之后 就可以进行实践判断和重绘

@Override protected void onDraw(Canvas canvas) {        //canvas.drawColor(0xFFCCCCCC);     //if you want another background color                   	//draw the balls on the canvas    	for (ColorBall ball : colorballs) {            canvas.drawBitmap(ball.getBitmap(), ball.getX(), ball.getY(), null);          }    }

?

public boolean onTouchEvent(MotionEvent event) {        int eventaction = event.getAction();                 int X = (int)event.getX();         int Y = (int)event.getY();         switch (eventaction ) {         case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on a ball        	balID = 0;        	for (ColorBall ball : colorballs) {        		// check if inside the bounds of the ball (circle)        		// get the center for the ball        		int centerX = ball.getX() + 25;        		int centerY = ball.getY() + 25;        		        		// calculate the radius from the touch to the center of the ball        		double radCircle  = Math.sqrt( (double) (((centerX-X)*(centerX-X)) + (centerY-Y)*(centerY-Y)));        		        		// if the radius is smaller then 23 (radius of a ball is 22), then it must be on the ball        		if (radCircle < 23){        			balID = ball.getID();                    break;        		}        		// check all the bounds of the ball (square)        		//if (X > ball.getX() && X < ball.getX()+50 && Y > ball.getY() && Y < ball.getY()+50){                //	balID = ball.getID();                //	break;                //}              }                          break;         case MotionEvent.ACTION_MOVE:   // touch drag with the ball        	// move the balls the same as the finger            if (balID > 0) {            	colorballs[balID-1].setX(X-25);            	colorballs[balID-1].setY(Y-25);            }        	            break;         case MotionEvent.ACTION_UP:        		// touch drop - just do things here after dropping             break;         }         // redraw the canvas        invalidate();         return true; 	    }

?

  相关解决方案