欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android實現(xiàn)圖片拖動效果

 更新時間:2017年03月07日 15:14:18   作者:ganchuanpu  
本文主要介紹了Android實現(xiàn)圖片拖動效果的實例,具有很好的參考價值。下面跟著小編一起來看下吧

要求:

1.通過手指移動來拖動圖片 

2.控制圖片不能超出屏幕顯示區(qū)域

技術(shù)點:

1.MotionEvent處理

2.對View進(jìn)行動態(tài)定位(layout)

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >
 <ImageView
  android:id="@+id/iv_main"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:src="@drawable/test"/>
</RelativeLayout>

MainActivity:

public class MainActivity extends Activity implements OnTouchListener {
 private ImageView iv_main;
 private RelativeLayout parentView;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  iv_main = (ImageView) findViewById(R.id.iv_main);
  parentView = (RelativeLayout) iv_main.getParent();
  /*
  int right = parentView.getRight(); //0
  int bottom = parentView.getBottom(); //0
  Toast.makeText(this, right+"---"+bottom, 1).show();
  */
  //設(shè)置touch監(jiān)聽
  iv_main.setOnTouchListener(this);
 }
 private int lastX;
 private int lastY;
 private int maxRight;
 private int maxBottom;
 @Override
 public boolean onTouch(View v, MotionEvent event) {
  //得到事件的坐標(biāo)
  int eventX = (int) event.getRawX();
  int eventY = (int) event.getRawY();
  switch (event.getAction()) {
  case MotionEvent.ACTION_DOWN:
   //得到父視圖的right/bottom
   if(maxRight==0) {//保證只賦一次值
    maxRight = parentView.getRight();
    maxBottom = parentView.getBottom();
   }
   //第一次記錄lastX/lastY
   lastX =eventX;
   lastY = eventY;
   break;
  case MotionEvent.ACTION_MOVE:
   //計算事件的偏移
   int dx = eventX-lastX;
   int dy = eventY-lastY;
   //根據(jù)事件的偏移來移動imageView
   int left = iv_main.getLeft()+dx;
   int top = iv_main.getTop()+dy;
   int right = iv_main.getRight()+dx;
   int bottom = iv_main.getBottom()+dy;
   //限制left >=0
   if(left<0) {
    right += -left;
    left = 0;
   }
   //限制top
   if(top<0) {
    bottom += -top;
    top = 0;
   }
   //限制right <=maxRight
   if(right>maxRight) {
    left -= right-maxRight;
    right = maxRight;
   }
   //限制bottom <=maxBottom
   if(bottom>maxBottom) {
    top -= bottom-maxBottom;
    bottom = maxBottom;
   }
   iv_main.layout(left, top, right, bottom);
   //再次記錄lastX/lastY
   lastX = eventX;
   lastY = eventY;
   break;
  default:
   break;
  }
  return true;//所有的motionEvent都交給imageView處理
 }
}

以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!

相關(guān)文章

最新評論