Android实现图片拖动效果

发布时间:2020-09-04 15:16:38 作者:ganchuanpu
来源:脚本之家 阅读:102

要求:

1.通过手指移动来拖动图片 

2.控制图片不能超出屏幕显示区域

技术点:

1.MotionEvent处理

2.对View进行动态定位(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();
  */
  //设置touch监听
  iv_main.setOnTouchListener(this);
 }
 private int lastX;
 private int lastY;
 private int maxRight;
 private int maxBottom;
 @Override
 public boolean onTouch(View v, MotionEvent event) {
  //得到事件的坐标
  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;
   //根据事件的偏移来移动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处理
 }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持亿速云!

推荐阅读:
  1. 基于JavaScript实现拖动滑块效果
  2. jquery如何实现拖动效果

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android 拖动 roi

上一篇:Python数据库小程序源代码

下一篇:vue如何在自定义组件中使用v-model

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》