• android开发之单点触摸


    相对于多点触摸,单点触摸还是很简单的。
    新建一个工程,先看看布局文件:

    <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"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.example.touchevent.MainActivity" >
    
        <ImageView
            android:id="@+id/iv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/jiafeimao"
            android:scaleType="matrix" />
    
    </RelativeLayout>

    就一个简单的ImageView,一会我们将在Activity中移动这个ImageView:

    public class MainActivity extends Activity {
    
        private ImageView iv;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            iv = (ImageView) this.findViewById(R.id.iv);
            iv.setOnTouchListener(new OnTouchListener() {
                private float x;
                private float y;
                // 用来操作图片的模型
                private Matrix oldMatrix = new Matrix();
                private Matrix newMatrix = new Matrix();
    
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) { // 判断操作类型
                    case MotionEvent.ACTION_DOWN:
                        //按下时记住x,y的坐标
                        x = event.getX();
                        y = event.getY();
                        oldMatrix.set(iv.getImageMatrix());
                        break;
                    case MotionEvent.ACTION_MOVE://移动时
                        //用另一个模型记住按下时的位置
                        newMatrix.set(oldMatrix);
                        //移动模型
                        newMatrix.setTranslate(event.getX()-x, event.getY()-y);
                        break;
                    }
                    //把图片放入移动后的模型中
                    iv.setImageMatrix(newMatrix);
                    return true;
                }
            });
        }
    }
    

    就是这么简单。

    完整代码下载

  • 相关阅读:
    eclipse经常卡死、反应慢、内存溢出的解决方案
    PAC4J 初探
    suse11离线安装nginx
    linux修改乱码的文件名
    CentOS修改服务器系统时间
    Unable to open nested entry '********.jar' 问题解决
    openssl req(生成证书请求和自建CA)
    CRT证书转JKS证书
    如何创建一个自签名的SSL证书(X509)
    Redis分布式锁的深度剖析
  • 原文地址:https://www.cnblogs.com/lenve/p/4517976.html
Copyright © 2020-2023  润新知