• Android通过手势实现图像拖拽功能


    本示例实现Android通过手势可以实现图像的拖拽功能。运行效果如下:

     

    代码如下:

    package com.android.drag;
    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.os.Bundle;
    import android.util.DisplayMetrics;
    import android.view.MotionEvent;
    import android.view.View;

    /**
     * Android通过手势实现图像拖拽功能
     * 
    @author Administrator
     *
     
    */
    public class DragActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // setContentView(R.layout.main);
            View view = new ImageDragView(this);
            
            setContentView(view);
        }

        class ImageDragView extends View {

            private float x1;
            private float y1;
            private float x2;
            private float y2;

            public ImageDragView(Context context) {
                super(context);
                // TODO Auto-generated constructor stub
            }

            @Override
            public boolean onTouchEvent(MotionEvent event) {
                // TODO Auto-generated method stub

                float size = event.getSize();

                int szi = (int) size;
                int dxi = szi >> 12;
                int dyit = ((1 << 12) - 1);
                int dyi = szi & dyit;

                DisplayMetrics metrics = getResources().getDisplayMetrics();
                
                float dx = metrics.widthPixels * dxi / (float) dyit;
                float dy = metrics.heightPixels * dyi / (float) dyit;

                x1 = event.getX();
                y1 = event.getY();

                x2 = x1 + dx;
                y2 = y1 + dy;

                invalidate();

                return true;
            }

            @Override
            protected void onDraw(Canvas canvas) {
                // TODO Auto-generated method stub
                super.onDraw(canvas);

                float r = (float) Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2)
                        * (y1 - y2)) / 2;
                r = 100 >= r ? 100 : r;

                Paint paint = new Paint();
                paint.setColor(Color.RED);
                canvas.drawCircle(x1, y1, r, paint);
            }
        }

    }  


    最后,希望转载的朋友能够尊重作者的劳动成果,加上转载地址:http://www.cnblogs.com/hanyonglu/archive/2012/02/13/2348553.html 谢谢。

    完毕。^_^ 

  • 相关阅读:
    Java实现 LeetCode 32 最长有效括号
    Java实现 LeetCode 31下一个排列
    Java实现 LeetCode 31下一个排列
    Java实现 LeetCode 31下一个排列
    Java实现 蓝桥杯 素因子去重
    Java实现 蓝桥杯 素因子去重
    Java实现 蓝桥杯 素因子去重
    Java实现 LeetCode 30 串联所有单词的子串
    Visual c++例子,可不使用常规的对话框资源模板的情况下,动态创建对话框的方法
    MFC不使用对话框资源模版创建对话框
  • 原文地址:https://www.cnblogs.com/hanyonglu/p/2348553.html
Copyright © 2020-2023  润新知