Android在界面中随意移动一个图片

来源:互联网 发布:男女审美差异 知乎 编辑:程序博客网 时间:2024/05/22 04:28

比较简单,没什么要说到的,直接看实现的代码

.xml  <ImageView        android:id="@+id/iv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:src="@drawable/ic_launcher" />.javapublic class MainActivity extends ActionBarActivity {    private ImageView iv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        iv = (ImageView) findViewById(R.id.iv);        iv.setOnTouchListener(new OnTouchListener() {            int maxwidth;            int maxheight;            int preX;// 上一次操作的x的坐标            int preY;// 上一次操作的Y坐标            @Override            public boolean onTouch(View v, MotionEvent event) {                // 获取当前坐标                int rawX = (int) event.getRawX();                int rawY = (int) event.getRawY();                switch (event.getAction()) {                case MotionEvent.ACTION_DOWN:                    if (maxwidth == 0) {                        RelativeLayout ivparent = (RelativeLayout) iv                                .getParent();                        maxwidth = ivparent.getWidth();                        maxheight = ivparent.getHeight();                    }                    preX = rawX;                    preY = rawY;                    break;                case MotionEvent.ACTION_MOVE:                    // 获取当前x,y轴移动的距离                    int dx = rawX - preX;                    int dy = rawY - preY;                    // 获取当前图片的四个值                    int left = iv.getLeft() + dx;                    int top = iv.getTop() + dy;                    int right = iv.getRight() + dx;                    int bottm = iv.getBottom() + dy;                    if (left < 0) {                        right = right - left;                        left = 0;                    }                    //限制right                    if(right > maxwidth){                        left = left - (right - maxwidth);                        right = maxwidth;                    }                    if (top < 0) {                        bottm = bottm - top;                        top = 0;                    }                    if (bottm >maxheight) {                        top = top - (bottm-maxheight);                        bottm = maxheight;                    }                    iv.layout(left, top, right, bottm);                    // 从新给初始值赋值                    preX = rawX;                    preY = rawY;                    break;                }                return true;            }        });    }}
0 0