Search code examples
androidxamarincamerazooming

How to use android camera zoom on my custom camera?


I did my job on making custom camera app with using xamarin. I rendered camera and now I have to implement zoom function. However, I don't know how to do it. I searched and found there is startSmoothZoom(int ). But how can I use this? Is there any example? I call that function when device recognize pinch gesture. Thank you in advance.


Solution

  •     private float oldDist = 1f;//to caculate Zoom in/out
        public override bool OnTouchEvent(MotionEvent e)
        {
            if (e.PointerCount == 1) {
            }
            switch (e.Action & MotionEventActions.Mask)
            {
                case MotionEventActions.Down:
                    oldDist = getFingerSpacing(e);
                    break;
                case MotionEventActions.Move:
                    float newDist = getFingerSpacing(e);
                    if (newDist > oldDist) {
                        //mCamera is your Camera which used to take picture, it should already exit in your custom Camera
                        handleZoom(true, mCamera);
                    } else if (newDist<oldDist) {
                        handleZoom(false, mCamera);
            }
                    oldDist = newDist;
                    break;
            }
            return true;
        }
    
        //get fingers's distance
        private static float getFingerSpacing(MotionEvent e)
        {
            float x = e.GetX(0) - e.GetX(1);
            float y = e.GetY(0) - e.GetY(1);
            return (float)Math.Sqrt(x * x + y * y);
        }
        //Zoom
        private void handleZoom(Boolean isZoomIn, Camera camera)
        {
            Camera.Parameters parameters = camera.GetParameters();
            if (parameters.IsZoomSupported) {
                int maxZoom = parameters.MaxZoom;
                int zoom = parameters.Zoom;
                if (isZoomIn && zoom < maxZoom)
                {
                    zoom++;
                }
                else if (zoom > 0)
                {
                    zoom--;
                }
                parameters.Zoom=zoom;
                camera.SetParameters(parameters);
            } else {
                Android.Util.Log.Error("lv", "zoom not supported");
            }
        }
    }