Android - 手勢縮放 - ScaleGestureDetector

摘要:Android - 手勢縮放 - ScaleGestureDetector

因為想研究怎麼做照像機的手勢縮放,

而找到一篇文章

http://android-innovation.blogspot.tw/2013/07/how-to-implement-pinch-and-pan-zoom-on.html

得知有一個手勢偵測的類別ScaleGestureDetector

 

利用OnTouch事件,將ScaleGestureDetector設定

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // Let the ScaleGestureDetector inspect all events.
        mScaleDetector.onTouchEvent(ev);
        return true;
    }    

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();            
            // Don't let the object get too small or too large.
            mScaleFactor = Math.max(0.5f, Math.min(mScaleFactor, 2.0f));

            //DoSomething

            invalidate();
            return true;
        }
    }

 

利用mScaleFactor為目前縮放比例,去設定各種需求

 

因為我要用在Camera

所以先瞭解,一開始的Zoom,及MaxZoom

        Parameters parameter = camera.getParameters();
        maxZoom = parameter.getMaxZoom();
        minZoom = parameter.getZoom();

用比例尺,去算出mScaleFactor對映的Zoom是多少,再將之設定

          parameter.setZoom(newZoom);            
           camera.setParameters(parameter); 

就可以完成手勢放大縮小照像機拍攝遠近了。