예제 #1
0
        public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
        {
            if (surfaceHolder.Surface == null)
            {
                return;
            }
            try
            {
                cameraInstance.StopPreview();
                cameraInstance.SetPreviewDisplay(surfaceHolder);

                Android.Hardware.Camera.Parameters parameters  = cameraInstance.GetParameters();
                Android.Hardware.Camera.Size       optimalSize = CameraHelpers.GetOptimalPreviewSize(context, cameraInstance, width, height);
                parameters.SetPreviewSize(optimalSize.Width, optimalSize.Height);
                parameters.SetPictureSize(optimalSize.Width, optimalSize.Height);
                parameters.FocusMode = Android.Hardware.Camera.Parameters.FocusModeContinuousPicture;
                cameraInstance.SetParameters(parameters);
                cameraInstance.SetDisplayOrientation(CameraHelpers.GetCameraOrientation(context));
                cameraInstance.StartPreview();
            }
            catch (Exception e)
            {
                Log.Debug("Camera activity", "Error starting camera preview: " + e.Message);
            }
        }
예제 #2
0
    public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
    {
        if (Holder.Surface == null)
        {
            return;
        }

        try
        {
            _camera.StopPreview();
        }
        catch (Exception)
        {
            // ignore: tried to stop a non-existent preview
        }

        try
        {
            // start preview with new settings
            _camera.SetPreviewDisplay(Holder);
            _camera.StartPreview();
        }
        catch (Exception e)
        {
            Log.Debug("", "Error starting camera preview: " + e.Message);
        }
    }
예제 #3
0
        public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
        {
            if (Holder.Surface == null)
            {
                return;
            }

            try
            {
                _camera.StopPreview();
            }
            catch (Exception e)
            {
                Log.Error("CAMERA_PREVIEW", "Error Stopping preview" + e.Message);
            }

            try
            {
                _camera.SetPreviewDisplay(Holder);
                _camera.StartPreview();
            }
            catch (Exception e)
            {
                Log.Debug("CAMERA_PREVIEW", "Error starting camera preview: " + e.Message);
            }
        }
예제 #4
0
        public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
        {
            if (Holder.Surface == null)
            {
                return;
            }

            try
            {
                camera.StopPreview();
            }
            catch (Exception)
            {
                // ignore: tried to stop a non-existent preview
            }

            try
            {
                // start preview with new settings
                camera.SetPreviewDisplay(Holder);
                camera.StartPreview();
            }
            catch (Exception e)
            {
            }
        }
예제 #5
0
        public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
        {
            if (holder.Surface == null)
            {
                return;
            }

            try
            {
                _mCamera.StopPreview();
            }
            catch (Exception e)
            {
                //TODO:KOA: remove Console!
                Console.WriteLine(Localization.Errors.ErrorCameraPreview + e.Message);
            }

            try
            {
                var p = _mCamera.GetParameters();
                p.SetPreviewSize(_mPreviewSize.Width, _mPreviewSize.Height);
                if (p.SupportedFocusModes.Contains(Android.Hardware.Camera.Parameters.FocusModeContinuousVideo))
                {
                    p.FocusMode = Android.Hardware.Camera.Parameters.FocusModeContinuousVideo;
                    _mCamera.SetParameters(p);
                }
                switch (Display.Rotation)
                {
                case SurfaceOrientation.Rotation0:
                    _mCamera.SetDisplayOrientation(90);
                    break;

                case SurfaceOrientation.Rotation90:
                    break;

                case SurfaceOrientation.Rotation180:
                    break;

                case SurfaceOrientation.Rotation270:
                    _mCamera.SetDisplayOrientation(180);
                    break;
                }
                p.SetPreviewSize(_mPreviewSize.Width, _mPreviewSize.Height);

                if (_mPictureSize != null)
                {
                    p.SetPictureSize(_mPictureSize.Width, _mPictureSize.Height);
                }
                p.SetRotation(90);
                _mCamera.SetParameters(p);
                _mCamera.SetPreviewDisplay(holder);
                _mCamera.StartPreview();
            }
            catch (Exception e)
            {
                //TODO:KOA: remove Console!
                Console.WriteLine(Localization.Errors.ErrorCameraPreview + e.Message);
            }
        }
예제 #6
0
 protected override void OnResume()
 {
     if (cameraReleased)
     {
         camera.Reconnect();
         camera.StartPreview();
         cameraReleased = false;
     }
     base.OnResume();
 }
예제 #7
0
 public void SurfaceCreated(ISurfaceHolder holder)
 {
     try
     {
         _camera.SetPreviewDisplay(holder);
         _camera.StartPreview();
     }
     catch
     {
     }
 }
예제 #8
0
 // 开启预览
 private void startPreview(bool checkPermission)
 {
     if (ActivityCompat.CheckSelfPermission(context, Manifest.Permission.Camera)
         != Permission.Granted)
     {
         if (checkPermission && permissionCallback != null)
         {
             permissionCallback.onRequestPermission();
         }
         return;
     }
     camera.StartPreview();
 }
예제 #9
0
        public void OnSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height)
        {
            _textureView.LayoutParameters =
                new FrameLayout.LayoutParams(width, height);

            try
            {
                _camera.SetPreviewTexture(surface);
                _camera.SetDisplayOrientation(90);
                _camera.StartPreview();
            }
            catch (Java.IO.IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    public void OnAutoFocus(bool success, Android.Hardware.Camera camera)
    {
        var parameters          = camera.GetParameters();
        var supportedFocusModes = parameters.SupportedFocusModes;

        var supportedFocusMode = cameraPage.GetSupportedFocusMode();

        parameters.FocusMode = supportedFocusMode;

        if (supportedFocusModes != null && supportedFocusModes.Any())
        {
            if (parameters.MaxNumFocusAreas > 0)
            {
                parameters.FocusAreas = null;
            }
            if (success)
            {
                TextView focusIndicatorTV = this.cameraPage.focusIndicator;
                focusIndicatorTV.SetX(tapX);
                focusIndicatorTV.SetY(tapY);
                focusIndicatorTV.Visibility = ViewStates.Visible;
            }
            else
            {
                TextView focusIndicatorTV = this.cameraPage.focusIndicator;
                focusIndicatorTV.Visibility = ViewStates.Gone;
            }
            camera.SetParameters(parameters);
            camera.StartPreview();
        }
    }
예제 #11
0
        static Task ToggleTorchAsync(bool switchOn)
        {
            return(Task.Run(() =>
            {
                lock (locker)
                {
                    if (Platform.HasApiLevel(BuildVersionCodes.M) && !AlwaysUseCameraApi)
                    {
                        var cameraManager = Platform.CameraManager;
                        foreach (var id in cameraManager.GetCameraIdList())
                        {
                            var hasFlash = cameraManager.GetCameraCharacteristics(id).Get(CameraCharacteristics.FlashInfoAvailable);
                            if (Java.Lang.Boolean.True.Equals(hasFlash))
                            {
                                cameraManager.SetTorchMode(id, switchOn);
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (camera == null)
                        {
                            if (surface == null)
                            {
                                surface = new SurfaceTexture(0);
                            }

#pragma warning disable CS0618 // Camera types are deprecated in Android 10+
                            camera = Camera.Open();

                            // Nexus 5 and some devices require a preview texture
                            camera.SetPreviewTexture(surface);
                        }

                        var param = camera.GetParameters();

                        // Deprecated in an earlier android version
                        param.FlashMode = switchOn ? Camera.Parameters.FlashModeTorch : Camera.Parameters.FlashModeOff;

                        camera.SetParameters(param);

                        if (switchOn)
                        {
                            camera.StartPreview();
                        }
                        else
                        {
                            camera.StopPreview();
                            camera.Release();
                            camera.Dispose();
#pragma warning restore CS0618 // Type or member is obsolete
                            camera = null;
                            surface.Dispose();
                            surface = null;
                        }
                    }
                }
            }));
        }
예제 #12
0
        private void InitCamera()
        {
            //bool success = false;
            //success = OpenCamera(0); //Try the face camera

            //if (success == false)
            //{
            //    success = OpenCamera(1); //Try the rear camera
            //}
            //variable to get the number of cameras in the device
            int cameraCount = Android.Hardware.Camera.NumberOfCameras;

            Android.Hardware.Camera.CameraInfo cameraInfo = new Android.Hardware.Camera.CameraInfo();
            for (int camIdx = 0; camIdx < cameraCount; camIdx++)
            {
                Android.Hardware.Camera.GetCameraInfo(camIdx, cameraInfo);
                if (cameraInfo.Facing == Android.Hardware.CameraFacing.Front)
                {
                    camera = Android.Hardware.Camera.Open(camIdx);

                    cameraId = camIdx;
                    camera.SetDisplayOrientation(90);
                }
            }
            //var video = Activity.FindViewById<VideoView>(Resource.Id.videoView1);
            //camera.SetPreviewDisplay(video.Holder);
            camera.AddCallbackBuffer(ss);
            camera.SetPreviewCallbackWithBuffer(new mPreviewCallback());
            camera.StartPreview();
        }
예제 #13
0
        public void SurfaceCreated(ISurfaceHolder holder)
        {
            //If authorisation not granted for camera
            if (ContextCompat.CheckSelfPermission(CurrentContext, Manifest.Permission.Camera) != Permission.Granted)
            {
                //ask for authorisation
                ActivityCompat.RequestPermissions(CurrentContext, new System.String[] { Manifest.Permission.Camera }, 50);
            }
            else
            {
                if (camera != null)
                {
                    camera.Release();
                    camera = null;
                }
                camera = Android.Hardware.Camera.Open();
                camera.SetDisplayOrientation(90);


                Parameters parameters = camera.GetParameters();
                parameters.FocusMode = Parameters.FocusModeContinuousVideo;
                camera.SetParameters(parameters);

                camera.SetPreviewDisplay(holder);
                camera.StartPreview();
                initRecorder();
                camera.Unlock();
            }

            prepareRecorder();
        }
 private void delete()
 {
     isRecording = false;
     rangeTime   = 0;
     ivStart.SetImageResource(Resource.Drawable.nim_video_capture_start_btn);
     ivBack.Visibility   = ViewStates.Gone;
     ivDelete.Visibility = ViewStates.Gone;
     try
     {
         if (camera != null)
         {
             camera.StartPreview();
         }
         chronometer.Base = SystemClock.ElapsedRealtime();
         System.IO.File.Delete(savePath);
     }
     catch (Exception ex)
     {
         Console.WriteLine("===delete error:" + ex);
     }
     finally
     {
         resetSavePath();
     }
 }
예제 #15
0
        public async Task GetPhoto()
        {
            _camera = Camera.Open();
            var parameters = _camera.GetParameters();

            var sizes = parameters.SupportedPictureSizes;

            int index = 0;

            for (int i = 0; i < sizes.Count; i++)
            {
                if (sizes[i].Width > 1200 && sizes[i].Width < 1300)
                {
                    index = i;
                }
            }

            parameters.SetPictureSize(sizes[index].Width, sizes[index].Height);
            parameters.SetRotation(90);
            parameters.SceneMode     = Camera.Parameters.SceneModeAuto;
            parameters.WhiteBalance  = Camera.Parameters.WhiteBalanceAuto;
            parameters.FocusMode     = Camera.Parameters.FocusModeContinuousPicture;
            parameters.PictureFormat = ImageFormatType.Jpeg;
            parameters.JpegQuality   = 100;
            _camera.SetParameters(parameters);
            _camera.SetPreviewCallback(this);
            _camera.Lock();
            SurfaceTexture st = new SurfaceTexture(100);

            _camera.SetPreviewTexture(st);
            _camera.StartPreview();

            await TakePicture();
        }
        public async Task <byte[]> TakePhoto()
        {
            _camera.StopPreview();
            var ratio = (decimal)Height / Width;
            var image = Bitmap.CreateBitmap(_liveView.Bitmap, 0, 0, _liveView.Bitmap.Width, (int)(_liveView.Bitmap.Width * ratio));

            byte[] imageBytes;
            using (var imageStream = new System.IO.MemoryStream())
            {
                await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 80, imageStream);

                image.Recycle();
                imageBytes = imageStream.ToArray();
            }
            _camera.StartPreview();
            return(imageBytes);
        }
예제 #17
0
        public async void TakePhoto2()
        {
            camera.StopPreview();
            var ratio = ((decimal)Height) / Width;
            var image = Bitmap.CreateBitmap(liveView.Bitmap, 0, 0, liveView.Bitmap.Width, (int)(liveView.Bitmap.Width * ratio));

            byte[] imageBytes = null;
            using (var imageStream = new System.IO.MemoryStream())
            {
                await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 50, imageStream);

                image.Recycle();
                imageBytes = imageStream.ToArray();
            }
            camera.StartPreview();
            outimageBytes = imageBytes;
        }
예제 #18
0
 public void OnPictureTaken(byte[] data, Android.Hardware.Camera camera)
 {
     try
     {
         ViewModel.CaptureCommand?.Execute(data);
         camera.StartPreview();
     }
     catch (System.Exception e)
     {
     }
 }
예제 #19
0
        private void OpenCamera()
        {
            if (CheckSelfPermission(Manifest.Permission.Camera) != Permission.Granted)
            {
                RequestCameraPermission();
                return;
            }

            camera = Open();
            Parameters parameters = camera.GetParameters();

            parameters.PictureFormat = ImageFormatType.Jpeg;
            parameters.PreviewFormat = ImageFormatType.Nv21;
            if (parameters.SupportedFocusModes.Contains(Parameters.FocusModeContinuousVideo))
            {
                parameters.FocusMode = Parameters.FocusModeContinuousVideo;
            }
            IList <Size> suportedPreviewSizes = parameters.SupportedPreviewSizes;
            int          i = 0;

            for (i = 0; i < suportedPreviewSizes.Count; i++)
            {
                if (suportedPreviewSizes[i].Width < 1300)
                {
                    break;
                }
            }
            parameters.SetPreviewSize(suportedPreviewSizes[i].Width, suportedPreviewSizes[i].Height);
            camera.SetParameters(parameters);
            camera.SetDisplayOrientation(90);
            camera.SetPreviewCallback(this);
            camera.SetPreviewDisplay(surface.Holder);
            camera.StartPreview();
            //Get camera width
            previewWidth = parameters.PreviewSize.Width;
            //Get camera height
            previewHeight = parameters.PreviewSize.Height;

            //Resize SurfaceView Size
            float scaledHeight = previewWidth * 1.0f * surface.Width / previewHeight;
            float prevHeight   = surface.Height;

            ViewGroup.LayoutParams lp = surface.LayoutParameters;
            lp.Width  = surface.Width;
            lp.Height = (int)scaledHeight;
            surface.LayoutParameters = lp;
            surface.Top = (int)((prevHeight - scaledHeight) / 2);
            surface.DrawingCacheEnabled = true;

            handlerThread = new HandlerThread("background");
            handlerThread.Start();
            //backgroundHandler = new MyHandler(handlerThread.Looper);
            backgroundHandler = new MyHandler(Looper.MainLooper);
        }
예제 #20
0
        public void SurfaceChanged(ISurfaceHolder holder, Android.Graphics.Format format, int w, int h)
        {
            // Now that the size is known, set up the camera parameters and begin
            // the preview.
            Camera.Parameters parameters = mCamera.GetParameters();
            parameters.SetPreviewSize(mPreviewSize.Width, mPreviewSize.Height);
            RequestLayout();

            mCamera.SetParameters(parameters);
            mCamera.StartPreview();
        }
예제 #21
0
        public void StartCamera(int camID, string flash, string resolution, string focuse)
        {
            StopCamera();
            try { mCamera = Android.Hardware.Camera.Open(camID); }
            catch (Exception)
            {
                try
                {
                    byte[] dataPacker = ((MainActivity)MainActivity.global_activity).MyDataPacker("CAMNOT", System.
                                                                                                  Text.Encoding.UTF8.GetBytes("vid"));
                    MainActivity.Soketimiz.BeginSend(dataPacker, 0, dataPacker.Length, SocketFlags.None, null, null);
                }
                catch (Exception) { }
                return;
            }

            Android.Hardware.Camera.Parameters params_ = mCamera.GetParameters();
            SetFlashModeOff(params_);
            if (flash == "1")
            {
                FlashParam(params_);
            }
            ///
            params_.SetPreviewSize(int.Parse(resolution.Split('x')[0]),
                                   int.Parse(resolution.Split('x')[1]));
            ///
            if (focuse == "1")
            {
                SetFocusModeOn(params_);
            }
            ///
            SetSceneModeAuto(params_);
            SetWhiteBalanceAuto(params_);
            mCamera.SetParameters(params_);
            try
            {
                mCamera.SetPreviewDisplay(hldr);
                mCamera.SetPreviewCallback(this);
                mCamera.StartPreview();
            }
            catch (Exception)
            {
                try
                {
                    byte[] senddata = ((MainActivity)MainActivity.global_activity).MyDataPacker("CAMNOT", Encoding.UTF8.GetBytes("Can't start camera"));
                    MainActivity.Soketimiz.BeginSend(senddata, 0, senddata.Length, SocketFlags.None, null, null);
                }
                catch (Exception) { }

                StopCamera();
                return;
            }
        }
예제 #22
0
 public void SurfaceCreated(ISurfaceHolder holder)
 {
     // throw new NotImplementedException();
     // open camera's parameters
     camera = Android.Hardware.Camera.Open();
     camera.SetDisplayOrientation(90);
     Android.Hardware.Camera.Parameters p = camera.GetParameters();
     p.PictureFormat = ImageFormatType.Jpeg;
     camera.SetParameters(p);
     camera.SetPreviewCallback(this);
     camera.SetPreviewDisplay(holder);
     camera.StartPreview();
 }
예제 #23
0
        /**
         * In addition to calling {@link Camera#startPreview()}, it also
         * updates the preview display that could be changed in some situations
         * @param holder the current {@link SurfaceHolder}
         */

        private async void StartCameraPreview(ISurfaceHolder holder)
        {
            try
            {
                _camera.SetPreviewDisplay(holder);
                _camera.StartPreview();
                _camera.AutoFocus(null);
            }
            catch (Exception e)
            {
                Console.WriteLine($"startCameraPreview(): error starting camera preview, {e}");
            }
        }
예제 #24
0
        public void OnSurfaceTextureAvailable(Android.Graphics.SurfaceTexture surface, int w, int h)
        {
            bool landscape = isLandScapeMode();

            if (!landscape)
            {
                m_TextureView.LayoutParameters = new FrameLayout.LayoutParams(DisplayWidth, DisplayHeight);
            }
            else
            {
                m_TextureView.LayoutParameters = new FrameLayout.LayoutParams(DisplayHeight, DisplayWidth);
            }

            SetScreenOrientation();

            try {
                m_Camera.SetPreviewTexture(surface);
                m_Camera.StartPreview();
            } catch (Java.IO.IOException e) {
                System.Console.WriteLine(e.Message);
            }
        }
예제 #25
0
        public async Task <byte[]> TakePhoto()
        {
            camera.StopPreview();
            var ratio = ((decimal)Height) / Width;

            float  degrees = 90;
            Matrix matrix  = new Matrix();

            matrix.SetRotate(degrees);
            var image = Bitmap.CreateBitmap(liveView.Bitmap, 0, 0, liveView.Bitmap.Width, (int)(liveView.Bitmap.Width * ratio), matrix, false);

            byte[] imageBytes = null;
            using (var imageStream = new System.IO.MemoryStream())
            {
                await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 50, imageStream);

                image.Recycle();
                imageBytes = imageStream.ToArray();
            }
            camera.StartPreview();
            return(imageBytes);
        }
        public void TurnOn()
        {
            // Additional information about using the camera light here:
            // http://forums.xamarin.com/discussion/24237/camera-led-or-flash
            // http://stackoverflow.com/questions/5503480/use-camera-flashlight-in-android?rq=1

            if (camera == null)
            {
                camera = Android.Hardware.Camera.Open();
            }

            if (camera == null)
            {
                Console.WriteLine("Camera failed to initialize");
                return;
            }

            var p = camera.GetParameters();
            var supportedFlashModes = p.SupportedFlashModes;

            if (supportedFlashModes == null)
            {
                supportedFlashModes = new List <string>();
            }

            var flashMode = string.Empty;

            if (supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeTorch))
            {
                flashMode = Android.Hardware.Camera.Parameters.FlashModeTorch;
            }

            if (!string.IsNullOrEmpty(flashMode))
            {
                p.FlashMode = flashMode;
                camera.SetParameters(p);
            }

            // nexus 5 fix here: http://stackoverflow.com/questions/21417332/nexus-5-4-4-2-flashlight-led-not-turning-on
            try
            {
                camera.SetPreviewTexture(new SurfaceTexture(0));
            }
            catch (IOException ex)
            {
                // Ignore
            }

            camera.StartPreview();
        }
예제 #27
0
            public Camera() : base(Forms.Context)
            {
                cam = Android.Hardware.Camera.Open();
#pragma warning restore 618
                Log("cam Opened");

                switch (
                    ((Android.Views.IWindowManager)Context.GetSystemService(Android.Content.Context.WindowService))
                    .DefaultDisplay.Rotation)
                {
                case Android.Views.SurfaceOrientation.Rotation0:
                    cam.SetDisplayOrientation(90);
                    break;

                case Android.Views.SurfaceOrientation.Rotation180:
                    cam.SetDisplayOrientation(270);
                    break;

                case Android.Views.SurfaceOrientation.Rotation270:
                    cam.SetDisplayOrientation(180);
                    break;

                case Android.Views.SurfaceOrientation.Rotation90:
                    cam.SetDisplayOrientation(0);
                    break;

                default:
                    break;
                }
                try
                {
                    cam.SetPreviewCallback(new Callback(
                                               (data, camera) =>
                    {
                        var Prev = Drawable;
                        using (var s = new System.IO.MemoryStream(data))
                            SetImageDrawable(new Android.Graphics.Drawables.BitmapDrawable(s));
                        Prev?.Dispose();
                    }
                                               ));
                    Log("Preview set");
                    cam.StartPreview();
                    Log("Preview started");
                }
                catch (Java.IO.IOException ex)
                {
                    Log(ex);
                }
            }
    public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
    {
        _camera = Android.Hardware.Camera.Open();

        try
        {
            _camera.SetPreviewTexture(surface);
            _camera.SetDisplayOrientation(90);
            _camera.StartPreview();
        }
        catch (Java.IO.IOException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
예제 #29
0
        public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
        {
            _camera = Android.Hardware.Camera.Open();

            try
            {
                _camera.SetPreviewTexture(surface);
                _camera.SetDisplayOrientation(90);     // возможно тут решение проблемы искажения при переворачивании
                _camera.StartPreview();
            }
            catch (Java.IO.IOException ex)
            {
                Console.WriteLine("OnSurfaceTextureAvailable - " + ex.Message);
            }
        }  // end of OnSurfaceTextureAvailable
예제 #30
0
        public void OnSurfaceTextureAvailable(SurfaceTexture surface, int w, int h)
        {
            _camera = Camera.Open();

            _textureView.LayoutParameters = new RelativeLayout.LayoutParams(w, h);

            try
            {
                _camera.SetPreviewTexture(surface);
                _camera.StartPreview();
            }
            catch (Java.IO.IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
예제 #31
0
 public void SurfaceCreated(ISurfaceHolder holder)
 {
     try
     {
         // if only front camera, get it
         camera = Camera.Open(0);
         Camera.Parameters p = camera.GetParameters();
         p.PictureFormat = Android.Graphics.ImageFormatType.Jpeg;
         camera.EnableShutterSound(true);
         // fix camera rotation
         camera.SetDisplayOrientation(0);
         camera.SetParameters(p);
         camera.SetPreviewCallback(this);
         camera.Lock();
         camera.SetPreviewDisplay(holder);
         camera.StartPreview();
     }
     catch (Java.IO.IOException e)
     {
     }
 }
예제 #32
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            var metrics = new DisplayMetrics();
            WindowManager.DefaultDisplay.GetRealMetrics(metrics);

            ScreenX = metrics.WidthPixels;
            ScreenY = metrics.HeightPixels;

            number = 0;
            SetContentView(Resource.Layout.CameraTakePicScreen);
            isRunning = false;
            var header = FindViewById<TextView>(Resource.Id.txtFirstScreenHeader);
            var btns = FindViewById<ImageView>(Resource.Id.imgNewUserHeader);
            var relLayout = FindViewById<RelativeLayout>(Resource.Id.relativeLayout1);
            ImageHelper.setupTopPanel(btns, header, relLayout, header.Context);

            Header.headertext = Application.Context.Resources.GetString(Resource.String.photoTitle);
            Header.fontsize = 32f;
            ImageHelper.fontSizeInfo(header.Context);
            header.SetTextSize(Android.Util.ComplexUnitType.Dip, Header.fontsize);
            header.Text = Header.headertext;

            var surface = FindViewById<SurfaceView>(Resource.Id.surfaceCameraView);

            holder = surface.Holder;
            holder.AddCallback(this);
            context = surface.Context;

            var takePicture = FindViewById<ImageButton>(Resource.Id.btnCamera);
            takePicture.Tag = 1;
            var flipView = FindViewById<ImageButton>(Resource.Id.imgFlipView);
            flipView.Tag = 2;
            var returnBack = FindViewById<ImageButton>(Resource.Id.imgBack);
            returnBack.Tag = 0;
            var bottom = FindViewById<LinearLayout>(Resource.Id.bottomHolder);

            var btn = new ImageButton[3];
            btn[0] = returnBack;
            btn[1] = takePicture;
            btn[2] = flipView;

            ImageHelper.setupButtonsPosition(btn, bottom, context);

            var cameraInfo = new Android.Hardware.Camera.CameraInfo();
            camera = null;

            int cameraCount = Android.Hardware.Camera.NumberOfCameras;
            if (cameraCount == 1)
                flipView.Visibility = ViewStates.Invisible;
            else
            {
                flipView.Click += delegate
                {
                    if (isRunning)
                    {
                        camera.StopPreview();
                        isRunning = false;
                        camera.Unlock();

                        if (cameraCount > 1 && camID < cameraCount - 1)
                            camID++;
                        else
                            camID--;

                        camera = Android.Hardware.Camera.Open(camID);
                        isRunning = true;

                        camera.Lock();
                        camera.StartPreview();
                    }
                };
            }
            takePicture.Click += delegate
            {
                var p = camera.GetParameters();
                p.PictureFormat = Android.Graphics.ImageFormatType.Jpeg;
                camera.SetParameters(p);
                camera.TakePicture(this, this, this);
            };

            returnBack.Click += (object sender, EventArgs e) =>
            {
                var resultData = new Intent();
                resultData.PutExtra("filename", fullFilename);
                SetResult(!string.IsNullOrEmpty(fullFilename) ? Result.Ok : Result.Canceled, resultData);
                Finish();
            };
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            number = 0;
            SetContentView(Resource.Layout.CameraTakePicScreen);
            isRunning = false;
            TextView header = FindViewById<TextView>(Resource.Id.txtFirstScreenHeader);
            ImageView btns = FindViewById<ImageView>(Resource.Id.imgNewUserHeader);
            RelativeLayout relLayout = FindViewById<RelativeLayout>(Resource.Id.relativeLayout1);
            ImageHelper.setupTopPanel(btns, header, relLayout, header.Context);

            Header.headertext = Application.Context.Resources.GetString(Resource.String.photoTitle);
            Header.fontsize = 36f;
            ImageHelper.fontSizeInfo(header.Context);
            header.SetTextSize(Android.Util.ComplexUnitType.Dip, Header.fontsize);
            header.Text = Header.headertext;

            SurfaceView surface = FindViewById<SurfaceView>(Resource.Id.surfaceCameraView);

            holder = surface.Holder;
            holder.AddCallback(this);
            holder.SetType(Android.Views.SurfaceType.PushBuffers);
            context = surface.Context;

            ImageButton takePicture = FindViewById<ImageButton>(Resource.Id.btnCamera);
            takePicture.Tag = 1;
            ImageButton flipView = FindViewById<ImageButton>(Resource.Id.imgFlipView);
            flipView.Tag = 2;
            ImageButton returnBack = FindViewById<ImageButton>(Resource.Id.imgBack);
            returnBack.Tag = 0;
            LinearLayout bottom = FindViewById<LinearLayout>(Resource.Id.bottomHolder);

            ImageButton[] btn = new ImageButton[3];
            btn [0] = returnBack;
            btn [1] = takePicture;
            btn [2] = flipView;

            ImageHelper.setupButtonsPosition(btn, bottom, context);

            int back = (int)Android.Hardware.CameraFacing.Back;
            int front = (int)Android.Hardware.CameraFacing.Front;

            Android.Hardware.Camera.CameraInfo cameraInfo = new Android.Hardware.Camera.CameraInfo();
            camera = null;

            int cameraCount = Android.Hardware.Camera.NumberOfCameras;
            if (cameraCount == 1)
                flipView.Visibility = ViewStates.Invisible;
            else
            {
                flipView.Click += delegate
                {
                    if (isRunning)
                    {
                        camera.StopPreview();
                        isRunning = false;
                        camera.Unlock();
                        //camera.Release();

                        if (cameraCount > 1 && camID < cameraCount - 1)
                            camID++;
                        else
                            camID--;

                        camera = Android.Hardware.Camera.Open(camID);
                        isRunning = true;

                        camera.Lock();
                        camera.StartPreview();
                    }
                };
            }
            takePicture.Click += delegate
            {
                Android.Hardware.Camera.Parameters p = camera.GetParameters();
                p.PictureFormat = Android.Graphics.ImageFormatType.Jpeg;
                camera.SetParameters(p);
                camera.TakePicture(this, this, this);
            };

            returnBack.Click += (object sender, EventArgs e) =>
            {
                Intent resultData = new Intent();
                resultData.PutExtra("filename", fullFilename);
                if (fullFilename != "")
                    SetResult(Result.Ok, resultData);
                else
                    SetResult(Result.Canceled, resultData);
                Finish();
            };
        }
		public override bool OnOptionsItemSelected (IMenuItem item) {
			// Handle item selection
			switch (item.ItemId) {
			case Resource.Id.switch_cam:
				// Release this camera -> mCameraCurrentlyLocked
				if (mCamera != null) {
					mCamera.StopPreview ();
					mPreview.SetCamera (null);
					mCamera.Release ();
					mCamera = null;
				}
				
				// Acquire the next camera and request Preview to reconfigure
				// parameters.
				mCamera = Camera.Open ((mCameraCurrentlyLocked + 1) % mNumberOfCameras);
				mCameraCurrentlyLocked = (mCameraCurrentlyLocked + 1)
					% mNumberOfCameras;
				mPreview.SwitchCamera (mCamera);
				
				// Start the preview
				mCamera.StartPreview();
				return true;
			case Android.Resource.Id.Home:
				Intent intent = new Intent (this.Activity, typeof (MainActivity));
				intent.AddFlags (ActivityFlags.ClearTop | ActivityFlags.SingleTop);
				StartActivity (intent);
				goto default;
			default:
				return base.OnOptionsItemSelected (item);
			}
		}