縮放系列(三):一個可以手勢縮放、拖拽、旋轉的layout


弄了一個下午,終於搞出來了,PowerfulLayout

下面是一個功能強大的改造的例子:

可以實現以下需求:

1.兩個手指進行縮放布局

2.所有子控件也隨着縮放,

3.子控件該有的功能不能丟失(像button有可被點擊的功能,縮放后不能丟失該功能)

相對上個例子,多了一個功能---

4.拖拽(平移)layout

 運行效果圖:http://pan.baidu.com/s/1geIoG8r

圖片太大就不貼出來了。

 

布局文件test.xml、超級簡單的

<?xml version="1.0" encoding="utf-8"?>
<com.example.testbitmapscale.PowerfulLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<FrameLayout
    android:background="@drawable/home_tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

        <ImageButton
            android:id="@+id/imageButton2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/selector_button1" />
</FrameLayout>


</com.example.testbitmapscale.PowerfulLayout>

 

java代碼:

MainActivity也是超級簡單

public class MainActivity extends ActionBarActivity {


    private View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.test);
        view = View.inflate(this, R.layout.test, null);
        setContentView(view);

        
    }

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        if (event.getPointerCount() > 1) {
//            // 多點觸控
//            // 返回給ScaleGestureDetector來處理
//            return mScaleGestureDetector.onTouchEvent(event);
//        } else {
//            // 單點觸控
//            switch (event.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                downX = (int) event.getX();
//                downY = (int) event.getY();
//                newHeight = view.getLayoutParams().height;
//                newWidth = view.getLayoutParams().width;
////                 int widthMeasureSpec =
////                 View.MeasureSpec.makeMeasureSpec(2000,View.MeasureSpec.AT_MOST);
////                
////                 int heightMeasureSpec
////                 =View.MeasureSpec.makeMeasureSpec(2000,View.MeasureSpec.AT_MOST);
////                
////                 view.measure(widthMeasureSpec,heightMeasureSpec);
////                
////                 newHeight = view.getMeasuredHeight();
////                
////                 newWidth = view.getMeasuredWidth();
//                break;
//            case MotionEvent.ACTION_MOVE:
//                long currentTimeMillis = System.currentTimeMillis();
//                if (currentTimeMillis - lastMultiTouchTime > 200) {
//                    // 雙指觸控后要等待200毫秒才能執行單指觸控的操作,避免雙指觸控后出現顫抖的情況
//                    int moveX = (int) event.getX();// 移動手指的時候手指的x
//                    int moveY = (int) event.getY();// 移動手指的時候手指的y
//                    int deltaX = (int) (moveX - downX);
//                    int deltaY = (int) (moveY - downY);
//                    int newLeft = left + deltaX;// view的新left
//                    int newTop = top + deltaY;// view的新top
//                    int newRight = right + deltaX;// view的新right
//                    int newBottom = bottom + deltaY;// view的新bottom
////                    int newWidth = (int) (preScale * originalWidth);
////                    int newHeight = (int) (preScale * originalHeight);
////                    if (deltaX>(newWidth-originalHeight)/2||deltaY>(newHeight-originalHeight)/2) {
////                        return false;
////                    }
//                    // int newWidth = view.getWidth();
//                    // int newHeight = view.getHeight();
//                    System.out.println("newWidth:" + newWidth + "newHeight:"
//                            + newHeight);
////                    System.out.println(preScale);
//                    if (newLeft < originalWidth - newWidth) {
//                        newLeft = originalWidth - newWidth;
//                        newRight = newLeft + newWidth;
//                    }
//                    // if (newTop < originalHeight - newHeight){
//                    // newTop = originalHeight - newHeight;
//                    // newBottom= newTop+newHeight;
//                    // }
//                    // if(newRight>originalWidth){
//                    // newRight=originalWidth;
//                    // newLeft=newRight-newWidth;
//                    // }
//                    // if(newBottom>originalHeight){
//                    // newBottom=originalHeight;
//                    // newTop=newBottom-newHeight;
//                    // }
//                    view.layout(newLeft, newTop, newRight, newBottom);// 重新擺放view的位置
//                } else {
//                    return false;
//                }
//
//                break;
//            case MotionEvent.ACTION_UP:
//                // 更新位置信息
//                left = view.getLeft();
//                top = view.getTop();
//                right = view.getRight();
//                bottom = view.getBottom();
//                break;
//
//            default:
//                break;
//            }
//            return true;// 代表消費了事件
//        }
//    }


}

PowerfulLayout.java:

package com.example.testbitmapscale;

import android.content.Context;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.FrameLayout;

import com.nineoldandroids.view.ViewHelper;

public class PowerfulLayout extends FrameLayout {
    // 屏幕寬高
    private int screenHeight;
    private int screenWidth;
    private ViewDragHelper mDragHelper;
    private long lastMultiTouchTime;// 記錄多點觸控縮放后的時間
    private int originalWidth;// view寬度
    private int originalHeight;// view高度
    private ScaleGestureDetector mScaleGestureDetector = null;
    // private View view;
    private int downX;// 手指按下的x坐標值
    private int downY;// 手指按下的y坐標值
    private int left;// view的左坐標值
    private int top;// view的上坐標值
    private int right;// view的右坐標值
    private int bottom;// view的下坐標值
    private int newHeight;
    private int newWidth;

    private float scale;
    private float preScale = 1;// 默認前一次縮放比例為1

    public PowerfulLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public PowerfulLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PowerfulLayout(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        mDragHelper = ViewDragHelper.create(this, callback);
        mScaleGestureDetector = new ScaleGestureDetector(context,
                new ScaleGestureListener());

        // view.post(new Runnable() {
        //
        // @Override
        // public void run() {
        // left = view.getLeft();
        // top = view.getTop();
        // right = view.getRight();
        // bottom = view.getBottom();
        // originalWidth = view.getWidth();
        // originalHeight = view.getHeight();
        // }
        // });
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        screenWidth = getMeasuredWidth();
        screenHeight = getMeasuredHeight();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        super.onInterceptTouchEvent(ev);
        boolean b = mDragHelper.shouldInterceptTouchEvent(ev);// 由mDragHelper決定是否攔截事件,並傳遞給onTouchEvent
        return b;
    }

    private boolean needToHandle=true;
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int pointerCount = event.getPointerCount(); // 獲得多少點
        if (pointerCount > 1) {// 多點觸控,
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                needToHandle=false;
                break;
            case MotionEvent.ACTION_MOVE:
                
                break;
            case MotionEvent.ACTION_POINTER_2_UP://第二個手指抬起的時候
                needToHandle=true;
                break;

            default:
                break;
            }
            return mScaleGestureDetector.onTouchEvent(event);//讓mScaleGestureDetector處理觸摸事件
        } else {
            long currentTimeMillis = System.currentTimeMillis();
            if (currentTimeMillis - lastMultiTouchTime > 200&&needToHandle) {
//                  多點觸控全部手指抬起后要等待200毫秒才能執行單指觸控的操作,避免多點觸控后出現顫抖的情況
                try {
                    mDragHelper.processTouchEvent(event);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
//            }
        }
        return false;
    }

    private ViewDragHelper.Callback callback = new ViewDragHelper.Callback() {
        /**
         * 用於判斷是否捕獲當前child的觸摸事件
         * 
         * @param child
         *            當前觸摸的子view
         * @param pointerId
         * @return true就捕獲並解析;false不捕獲
         */
        @Override
        public boolean tryCaptureView(View child, int pointerId) {
            if (preScale > 1)
                return true;
            return false;
        }

        /**
         * 控制水平方向上的位置
         */
        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {

            if (left < (screenWidth - screenWidth * preScale) / 2)
                left = (int) (screenWidth - screenWidth * preScale) / 2;// 限制mainView可向左移動到的位置
            if (left > (screenWidth * preScale - screenWidth) / 2)
                left = (int) (screenWidth * preScale - screenWidth) / 2;// 限制mainView可向右移動到的位置
            return left;
        }

        public int clampViewPositionVertical(View child, int top, int dy) {

            if (top < (screenHeight - screenHeight * preScale) / 2) {
                top = (int) (screenHeight - screenHeight * preScale) / 2;// 限制mainView可向上移動到的位置
            }
            if (top > (screenHeight * preScale - screenHeight) / 2) {
                top = (int) (screenHeight * preScale - screenHeight) / 2;// 限制mainView可向上移動到的位置
            }
            return top;
        }

    };

    public class ScaleGestureListener implements
            ScaleGestureDetector.OnScaleGestureListener {

        @Override
        public boolean onScale(ScaleGestureDetector detector) {

            float previousSpan = detector.getPreviousSpan();// 前一次雙指間距
            float currentSpan = detector.getCurrentSpan();// 本次雙指間距
            if (currentSpan < previousSpan) {
                // 縮小
                // scale = preScale-detector.getScaleFactor()/3;
                scale = preScale - (previousSpan - currentSpan) / 1000;
            } else {
                // 放大
                // scale = preScale+detector.getScaleFactor()/3;
                scale = preScale + (currentSpan - previousSpan) / 1000;
            }
            // 縮放view
            if (scale > 0.5) {
                ViewHelper.setScaleX(PowerfulLayout.this, scale);// x方向上縮放
                ViewHelper.setScaleY(PowerfulLayout.this, scale);// y方向上縮放
            }
            return false;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            // 一定要返回true才會進入onScale()這個函數
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            preScale = scale;// 記錄本次縮放比例
            lastMultiTouchTime = System.currentTimeMillis();// 記錄雙指縮放后的時間
        }
    }

}

 

可以手勢縮放、拖拽、旋轉的layout應用場景,例子:qq側滑菜單。側滑的時候菜單中所有子控件跟隨父控件從小變大,不過它不支持雙指縮放,只是單指操作。鏈接:http://blog.csdn.net/qq_30948129/article/details/52282451

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM