Пример #1
0
 // Retrieves the JPEG orientation from the specified screen rotation.
 private int GetOrientation(int rotation)
 {
     // Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X)
     // We have to take that into account and rotate JPEG properly.
     // For devices with orientation of 90, we simply return our mapping from ORIENTATIONS.
     // For devices with orientation of 270, we need to rotate the JPEG 180 degrees.
     return((ORIENTATIONS.Get(rotation) + mSensorOrientation + 270) % 360);
 }
        public int GetOrientation()
        {
            int rotation = (int)Activity.WindowManager.DefaultDisplay.Rotation;

            // Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X)
            // We have to take that into account and rotate JPEG properly.
            // For devices with orientation of 90, we simply return our mapping from ORIENTATIONS.
            // For devices with orientation of 270, we need to rotate the JPEG 180 degrees.
            return((Orientations.Get(rotation) + mSensorOrientation + 270) % 360);
        }
Пример #3
0
        private void SetUpMediaRecorder()
        {
            if (null == _context)
            {
                return;
            }
            mediaRecorder = new MediaRecorder();
            //changed this camcorder
            mediaRecorder.SetAudioSource(AudioSource.Camcorder);
            mediaRecorder.SetVideoSource(VideoSource.Surface);
            // mediaRecorder.SetOutputFormat(OutputFormat.Mpeg4);

            //profile should be set after audio and video source and before
            //setting the output file
            //set this for test A
            mediaRecorder.SetProfile(CamcorderProfile.Get(CamcorderQuality.High));

            string localFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);

            videoFilePath = System.IO.Path.Combine(localFolder, $"video_{DateTime.Now.ToString("yyMMdd_hhmmss")}.mp4");


            // var localPath = Android.OS.Environment.ExternalStorageDirectory + "/video1.mp4";
            mediaRecorder.SetOutputFile(videoFilePath);

            //mediaRecorder.SetVideoEncodingBitRate(10000000);
            //mediaRecorder.SetVideoFrameRate(30);

            // Call this after setOutFormat() but before prepare().
            mediaRecorder.SetVideoSize(videoSize.Width, videoSize.Height);

            //mediaRecorder.SetVideoEncoder(VideoEncoder.H264);
            //mediaRecorder.SetAudioEncoder(AudioEncoder.Aac);

            var windowManager = _context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>();
            int rotation      = (int)windowManager.DefaultDisplay.Rotation;
            int orientation   = ORIENTATIONS.Get(rotation);

            mediaRecorder.SetOrientationHint(orientation);
            mediaRecorder.Prepare();
        }
Пример #4
0
        private void startRecordingVideo()
        {
            if (null == Activity)
            {
                return;
            }


            media_recorder = new MediaRecorder();
            File file = getVideoFile(Activity);

            try {
                //UI
                button_video.SetText(Resource.String.stop);
                is_recording_video = true;

                //Configure the MediaRecorder
                media_recorder.SetAudioSource(AudioSource.Mic);
                media_recorder.SetVideoSource(VideoSource.Surface);
                media_recorder.SetOutputFormat(OutputFormat.Mpeg4);
                media_recorder.SetOutputFile(System.IO.Path.GetFullPath(file.ToString()));
                media_recorder.SetVideoEncodingBitRate(10000000);
                media_recorder.SetVideoFrameRate(30);
                media_recorder.SetVideoSize(1440, 1080);
                media_recorder.SetVideoEncoder(VideoEncoder.H264);
                media_recorder.SetAudioEncoder(AudioEncoder.Aac);
                int rotation    = (int)Activity.WindowManager.DefaultDisplay.Rotation;
                int orientation = ORIENTATIONS.Get(rotation);
                media_recorder.SetOrientationHint(orientation);
                media_recorder.Prepare();
                Surface surface = media_recorder.Surface;

                //Set up CaptureRequest
                builder = camera_device.CreateCaptureRequest(CameraTemplate.Record);
                builder.AddTarget(surface);
                var preview_surface = new Surface(texture_view.SurfaceTexture);
                builder.AddTarget(preview_surface);
                var surface_list = new List <Surface>();
                surface_list.Add(surface);
                surface_list.Add(preview_surface);
                camera_device.CreateCaptureSession(surface_list, new RecordingCaptureStateListener(this), null);
            } catch (IOException e) {
                e.PrintStackTrace();
            } catch (CameraAccessException e) {
                e.PrintStackTrace();
            } catch (IllegalStateException e) {
                e.PrintStackTrace();
            }
        }
Пример #5
0
        public int GetOrientation()
        {
            // Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X)
            // We have to take that into account and rotate JPEG properly.
            // For devices with orientation of 90, we simply return our mapping from ORIENTATIONS.
            // For devices with orientation of 270, we need to rotate the JPEG 180 degrees.

            var windowManager   = Application.Context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>();
            int displayRotation = (int)windowManager.DefaultDisplay.Rotation;

            var characteristics = _manager.GetCameraCharacteristics(_cameraId);

            mSensorOrientation = (int)characteristics.Get(CameraCharacteristics.SensorOrientation);
            return((ORIENTATIONS.Get(displayRotation) + mSensorOrientation + 270) % 360);
        }
Пример #6
0
        private void TakePicture()
        {
            try
            {
                Activity activity = Activity;
                if (activity == null || mCameraDevice == null)
                {
                    return;
                }
                CameraManager manager = (CameraManager)activity.GetSystemService(Android.Content.Context.CameraService);

                spinner.Visibility = ViewStates.Visible;

                // Pick the best JPEG size that can be captures with this CameraDevice
                CameraCharacteristics characteristics = manager.GetCameraCharacteristics(mCameraDevice.Id);
                Android.Util.Size[]   jpegSizes       = null;
                if (characteristics != null)
                {
                    jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);
                }

                width  = 640;
                height = 480;
                int total             = width * height;
                int targetRes         = 3145728; //About 5MP
                int currentTargetDiff = System.Math.Abs((width * height) - targetRes);;

                if (jpegSizes != null && jpegSizes.Length > 0)
                {
                    foreach (Android.Util.Size size in jpegSizes)
                    {
                        int targetDiff = System.Math.Abs((size.Width * size.Height) - targetRes);
                        if (targetDiff < currentTargetDiff)
                        {
                            width             = size.Width;
                            height            = size.Height;
                            currentTargetDiff = targetDiff;
                        }
                    }
                }

                // We use an ImageReader to get a JPEG from CameraDevice
                // Here, we create a new ImageReader and prepare its Surface as an output from the camera
                ImageReader    reader         = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1);
                List <Surface> outputSurfaces = new List <Surface>();
                outputSurfaces.Add(reader.Surface);
                //outputSurfaces.Add(new Surface(textureView.SurfaceTexture));

                CaptureRequest.Builder captureBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
                captureBuilder.AddTarget(reader.Surface);
                SetUpCaptureRequestBuilder(captureBuilder);
                // Orientation
                SurfaceOrientation rotation = activity.WindowManager.DefaultDisplay.Rotation;
                captureBuilder.Set(CaptureRequest.JpegOrientation, new Java.Lang.Integer(ORIENTATIONS.Get((int)rotation)));

                Java.IO.File file = new Java.IO.File(activity.GetExternalFilesDir(null), "pic.jpg");

                // This listener is called when an image is ready in ImageReader
                // Right click on ImageAvailableListener in your IDE and go to its definition
                ImageAvailableListener readerListener = new ImageAvailableListener(this);

                // We create a Handler since we want to handle the resulting JPEG in a background thread
                HandlerThread thread = new HandlerThread("CameraPicture");
                thread.Start();
                Handler backgroundHandler = new Handler(thread.Looper);
                reader.SetOnImageAvailableListener(readerListener, backgroundHandler);

                //This listener is called when the capture is completed
                // Note that the JPEG data is not available in this listener, but in the ImageAvailableListener we created above
                // Right click on CameraCaptureListener in your IDE and go to its definition
                CameraCaptureListener captureListener = new CameraCaptureListener()
                {
                    Page = this
                };


                mCameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener()
                {
                    OnConfiguredAction = (CameraCaptureSession session) => {
                        try
                        {
                            CaptureRequest capReq = captureBuilder.Build();
                            session.Capture(capReq, captureListener, backgroundHandler);
                        }
                        catch (CameraAccessException ex)
                        {
                            Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
                        }
                    },
                    OnConfigureFailedAction = (CameraCaptureSession session) => {
                        Log.WriteLine(LogPriority.Error, "Session setup error", session.ToString());
                    }
                }, backgroundHandler);
            }
            catch (CameraAccessException ex)
            {
                Log.WriteLine(LogPriority.Info, "Taking picture error: ", ex.StackTrace);
            }
        }
 int GetOrientation(int rotation) => (_orientations.Get(rotation) + sensorOrientation + 270) % 360;
Пример #8
0
        /// <summary>
        /// Takes the photo.
        /// </summary>
        public void TakePhoto()
        {
            if (_context != null && _cameraDevice != null)
            {
                try
                {
                    Busy?.Invoke(this, true);

                    if (_mediaSoundLoaded)
                    {
                        _mediaSound.Play(MediaActionSoundType.ShutterClick);
                    }

                    // Pick the best JPEG size that can be captures with this CameraDevice
                    var    characteristics = _manager.GetCameraCharacteristics(_cameraDevice.Id);
                    Size[] jpegSizes       = null;
                    if (characteristics != null)
                    {
                        jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.RawSensor);
                    }
                    int width  = 640;
                    int height = 480;

                    if (jpegSizes != null && jpegSizes.Length > 0)
                    {
                        width  = jpegSizes[0].Width;
                        height = jpegSizes[0].Height;
                    }

                    // We use an ImageReader to get a JPEG from CameraDevice
                    // Here, we create a new ImageReader and prepare its Surface as an output from the camera
                    var reader         = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1);
                    var outputSurfaces = new List <Surface>(2);
                    outputSurfaces.Add(reader.Surface);
                    outputSurfaces.Add(new Surface(_viewSurface));

                    CaptureRequest.Builder captureBuilder = _cameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
                    captureBuilder.AddTarget(reader.Surface);
                    captureBuilder.Set(CaptureRequest.ControlMode, new Integer((int)ControlMode.Auto));

                    // Orientation
                    var windowManager           = _context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>();
                    SurfaceOrientation rotation = windowManager.DefaultDisplay.Rotation;

                    captureBuilder.Set(CaptureRequest.JpegOrientation, new Integer(ORIENTATIONS.Get((int)rotation)));

                    // This listener is called when an image is ready in ImageReader
                    ImageAvailableListener readerListener = new ImageAvailableListener();

                    readerListener.ImageProcessingCompleted += (sender, e) =>
                    {
                        Photo?.Invoke(this, e);
                    };

                    // We create a Handler since we want to handle the resulting JPEG in a background thread
                    HandlerThread thread = new HandlerThread("CameraPicture");
                    thread.Start();
                    Handler backgroundHandler = new Handler(thread.Looper);
                    reader.SetOnImageAvailableListener(readerListener, backgroundHandler);

                    var captureListener = new CameraCaptureListener();

                    captureListener.PhotoComplete += (sender, e) =>
                    {
                        Busy?.Invoke(this, false);
                        StartPreview();
                    };

                    _cameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener()
                    {
                        OnConfiguredAction = (CameraCaptureSession session) =>
                        {
                            try
                            {
                                _previewSession = session;
                                session.Capture(captureBuilder.Build(), captureListener, backgroundHandler);
                            }
                            catch (CameraAccessException ex)
                            {
                                Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
                            }
                        }
                    }, backgroundHandler);
                }
                catch (CameraAccessException error)
                {
                    Log.WriteLine(LogPriority.Error, error.Source, error.Message);
                }
                catch (Java.Lang.Exception error)
                {
                    Log.WriteLine(LogPriority.Error, error.Source, error.Message);
                }
            }
        }
Пример #9
0
 public static int GetOrientation(SurfaceOrientation rotation)
 {
     return(Orientations.Get((int)rotation));
 }
Пример #10
0
        public void TakePhoto()
        {
            if (_context == null || CameraDevice == null)
            {
                return;
            }

            var characteristics = _manager.GetCameraCharacteristics(CameraDevice.Id);

            Size[] jpegSizes = null;
            if (characteristics != null)
            {
                jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);
            }
            var width  = 480;
            var height = 640;

            if (jpegSizes != null && jpegSizes.Length > 0)
            {
                width  = jpegSizes[0].Width;
                height = jpegSizes[0].Height;
            }

            var reader         = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1);
            var outputSurfaces = new List <Surface>(2)
            {
                reader.Surface, new Surface(_viewSurface)
            };

            var captureBuilder = CameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);

            captureBuilder.AddTarget(reader.Surface);
            captureBuilder.Set(CaptureRequest.ControlMode, new Integer((int)ControlMode.Auto));

            var windowManager = _context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>();
            var rotation      = windowManager.DefaultDisplay.Rotation;

            captureBuilder.Set(CaptureRequest.JpegOrientation, new Integer(Orientations.Get((int)rotation)));

            var readerListener = new ImageAvailableListener();

            readerListener.Photo += (sender, buffer) =>
            {
                Photo?.Invoke(this, ImageSource.FromStream(() => new MemoryStream(buffer)));
            };

            var thread = new HandlerThread("CameraPicture");

            thread.Start();
            var backgroundHandler = new Handler(thread.Looper);

            reader.SetOnImageAvailableListener(readerListener, backgroundHandler);

            var captureListener = new CameraCaptureListener();

            captureListener.PhotoComplete += (sender, e) =>
            {
                StartPreview();
            };

            CameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener
            {
                OnConfiguredAction = session =>
                {
                    try
                    {
                        _previewSession = session;
                        session.Capture(captureBuilder.Build(), captureListener, backgroundHandler);
                    }
                    catch (CameraAccessException ex)
                    {
                        Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
                    }
                }
            }, backgroundHandler);
        }
        protected override void OnScrollChanged(int l, int t, int oldl, int oldt)
        {
            base.OnScrollChanged(l, t, oldl, oldt);
            if (_mCallbacks != null)
            {
                if (ChildCount > 0)
                {
                    int firstVisiblePosition = GetChildAdapterPosition(GetChildAt(0));
                    int lastVisiblePosition  = GetChildAdapterPosition(GetChildAt(ChildCount - 1));
                    for (int i = firstVisiblePosition, j = 0; i <= lastVisiblePosition; i++, j++)
                    {
                        int  childHeight = 0;
                        View child       = GetChildAt(j);
                        if (child != null)
                        {
                            if (_mChildrenHeights.IndexOfKey(i) < 0 || (child.Height != _mChildrenHeights.Get(i)))
                            {
                                childHeight = child.Height;
                            }
                        }
                        _mChildrenHeights.Put(i, childHeight);
                    }

                    View firstVisibleChild = GetChildAt(0);
                    if (firstVisibleChild != null)
                    {
                        if (_mPrevFirstVisiblePosition < firstVisiblePosition)
                        {
                            // scroll down
                            int skippedChildrenHeight = 0;
                            if (firstVisiblePosition - _mPrevFirstVisiblePosition != 1)
                            {
                                for (int i = firstVisiblePosition - 1; i > _mPrevFirstVisiblePosition; i--)
                                {
                                    if (0 < _mChildrenHeights.IndexOfKey(i))
                                    {
                                        skippedChildrenHeight += _mChildrenHeights.Get(i);
                                    }
                                    else
                                    {
                                        // Approximate each item's height to the first visible child.
                                        // It may be incorrect, but without this, scrollY will be broken
                                        // when scrolling from the bottom.
                                        skippedChildrenHeight += firstVisibleChild.Height;
                                    }
                                }
                            }
                            _mPrevScrolledChildrenHeight += _mPrevFirstVisibleChildHeight + skippedChildrenHeight;
                            _mPrevFirstVisibleChildHeight = firstVisibleChild.Height;
                        }
                        else if (firstVisiblePosition < _mPrevFirstVisiblePosition)
                        {
                            // scroll up
                            int skippedChildrenHeight = 0;
                            if (_mPrevFirstVisiblePosition - firstVisiblePosition != 1)
                            {
                                for (int i = _mPrevFirstVisiblePosition - 1; i > firstVisiblePosition; i--)
                                {
                                    if (0 < _mChildrenHeights.IndexOfKey(i))
                                    {
                                        skippedChildrenHeight += _mChildrenHeights.Get(i);
                                    }
                                    else
                                    {
                                        // Approximate each item's height to the first visible child.
                                        // It may be incorrect, but without this, scrollY will be broken
                                        // when scrolling from the bottom.
                                        skippedChildrenHeight += firstVisibleChild.Height;
                                    }
                                }
                            }
                            _mPrevScrolledChildrenHeight -= firstVisibleChild.Height + skippedChildrenHeight;
                            _mPrevFirstVisibleChildHeight = firstVisibleChild.Height;
                        }
                        else if (firstVisiblePosition == 0)
                        {
                            _mPrevFirstVisibleChildHeight = firstVisibleChild.Height;
                            _mPrevScrolledChildrenHeight  = 0;
                        }
                        if (_mPrevFirstVisibleChildHeight < 0)
                        {
                            _mPrevFirstVisibleChildHeight = 0;
                        }
                        _mScrollY = _mPrevScrolledChildrenHeight - firstVisibleChild.Top;
                        _mPrevFirstVisiblePosition = firstVisiblePosition;

                        _mCallbacks.OnScrollChanged(_mScrollY, _mFirstScroll, _mDragging);
                        if (_mFirstScroll)
                        {
                            _mFirstScroll = false;
                        }

                        if (_mPrevScrollY < _mScrollY)
                        {
                            //down
                            _mScrollState = ObservableScrollState.Up;
                        }
                        else if (_mScrollY < _mPrevScrollY)
                        {
                            //up
                            _mScrollState = ObservableScrollState.Down;
                        }
                        else
                        {
                            _mScrollState = ObservableScrollState.Stop;
                        }
                        _mPrevScrollY = _mScrollY;
                    }
                }
            }
        }
Пример #12
0
        private void startCamera()
        {
            if (ContextCompat.CheckSelfPermission(context, Manifest.Permission.Camera)
                != Android.Content.PM.Permission.Granted)
            {
                if (permissionCallback != null)
                {
                    permissionCallback.onRequestPermission();
                }
                return;
            }
            if (camera == null)
            {
                Android.Hardware.Camera.CameraInfo cameraInfo = new Android.Hardware.Camera.CameraInfo();
                for (int i = 0; i < Android.Hardware.Camera.NumberOfCameras; i++)
                {
                    Android.Hardware.Camera.GetCameraInfo(i, cameraInfo);
                    if ((int)cameraInfo.Facing == cameraFacing)
                    {
                        cameraId = i;
                    }
                }
                camera = Android.Hardware.Camera.Open(cameraId);
            }
            //        if (parameters == null) {
            //            parameters = camera.getParameters();
            //            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            //        }


            int detectRotation = 0;

            if (cameraFacing == 1)
            {
                int rotation = ORIENTATIONS.Get(displayOrientation);
                rotation = getCameraDisplayOrientation(rotation, cameraId, camera);
                camera.SetDisplayOrientation(rotation);
                detectRotation = rotation;
                if (displayOrientation == 0)
                {
                    if (detectRotation == 90 || detectRotation == 270)
                    {
                        detectRotation = (detectRotation + 180) % 360;
                    }
                }
            }
            else if (cameraFacing == 0)
            {
                int rotation = ORIENTATIONS.Get(displayOrientation);
                rotation = getCameraDisplayOrientation(rotation, cameraId, camera);
                camera.SetDisplayOrientation(rotation);
                detectRotation = rotation;
            }
            else if (cameraFacing == 2)
            {
                camera.SetDisplayOrientation(0);
                detectRotation = 0;
            }

            opPreviewSize(preferredWidth, preferredHeight);
            Android.Hardware.Camera.Size size = camera.GetParameters().PreviewSize;
            if (detectRotation % 180 == 90)
            {
                previewView.setPreviewSize(size.Height, size.Width);
            }
            else
            {
                previewView.setPreviewSize(size.Width, size.Height);
            }
            int temp = detectRotation;

            try
            {
                // if (cameraFacing == ICameraControl.CAMERA_USB) {
                // camera.SetPreviewTexture(textureView.getSurfaceTexture());
                //            } else {
                //            surfaceTexture = new SurfaceTexture(11);
                //            camera.setPreviewTexture(surfaceTexture);
                //            uiHandler.post(new Runnable() {
                //                @Override
                //                public void run() {
                //
                //                    if (textureView != null) {
                //                        surfaceTexture.detachFromGLContext();
                //                        textureView.setSurfaceTexture(surfaceTexture);
                //                    }
                //                }
                //            });
                // }
                //            camera.addCallbackBuffer(new byte[size.width * size.height * 3 / 2]);
                //            camera.setPreviewCallbackWithBuffer(new Camera.PreviewCallback() {
                //
                //                @Override
                //                public void onPreviewFrame(byte[] data, Camera camera) {
                //                    Log.i("wtf", "onPreviewFrame-->");
                //                    onFrameListener.onPreviewFrame(data, temp, size.width, size.height);
                //                    camera.addCallbackBuffer(data);
                //           ad     }
                //            });
                //    camera.setPreviewCallback(new Camera.PreviewCallback() {

                //    public void onPreviewFrame(byte[] data, Camera camera)
                //    {
                //        LogUtil.i("wtf", "onPreviewFrame-->");
                //        onFrameListener.onPreviewFrame(data, temp, size.width, size.height);
                //    }
                //});
            }
            catch (IOException e)
            {
                e.PrintStackTrace();
                LogUtil.i("wtf", e.ToString());
            }
            catch (RuntimeException e)
            {
                e.PrintStackTrace();
                LogUtil.i("wtf", e.ToString());
            }
        }
Пример #13
0
        //    private  CameraDevice.StateCallback deviceStateCallback = new CameraDevice.StateCallback()
        //    {


        //    public void onOpened(@NonNull CameraDevice cameraDevice)
        //    {
        //        cameraLock.release();
        //        Camera2Control.this.cameraDevice = cameraDevice;
        //        createCameraPreviewSession();
        //    }


        //    public void onDisconnected(@NonNull CameraDevice cameraDevice)
        //    {
        //        cameraLock.release();
        //        cameraDevice.close();
        //        Camera2Control.this.cameraDevice = null;
        //    }


        //    public void onError(@NonNull CameraDevice cameraDevice, int error)
        //    {
        //        cameraLock.release();
        //        cameraDevice.close();
        //        Camera2Control.this.cameraDevice = null;
        //    }
        //};

        private void createCameraPreviewSession()
        {
            try
            {
                if (surfaceTexture == null)
                {
                    surfaceTexture = new SurfaceTexture(11); // TODO
                }

                if (textureView != null)
                {
                    //    handler.post(new Runnable()
                    //    {


                    //    public void run()
                    //    {
                    //        try
                    //        {
                    //            surfaceTexture.detachFromGLContext();
                    //        }
                    //        catch (Exception e)
                    //        {
                    //            e.printStackTrace();
                    //        }
                    //        if (textureView.getSurfaceTexture() != surfaceTexture)
                    //        {
                    //            textureView.setSurfaceTexture(surfaceTexture);
                    //        }
                    //    }
                    //});
                }

                Surface surface  = new Surface(surfaceTexture);
                int     rotation = ORIENTATIONS.Get(orientation);
                if (rotation % 180 == 90)
                {
                    surfaceTexture.SetDefaultBufferSize(preferredWidth, preferredHeight);
                }
                else
                {
                    surfaceTexture.SetDefaultBufferSize(preferredHeight, preferredWidth);
                }
                previewRequestBuilder = cameraDevice.CreateCaptureRequest(CameraTemplate.Preview);
                previewRequestBuilder.AddTarget(surface);

                imageReader = ImageReader.NewInstance(preferredWidth, preferredHeight, ImageFormat.Yuv420888, 2);
                //    imageReader.SetOnImageAvailableListener(new OnImageAvailableListener()
                //    {


                //    public void onImageAvailable(ImageReader reader)
                //    {
                //    }
                //}, backgroundHandler);

                previewRequestBuilder.AddTarget(imageReader.Surface);

                updateFlashMode(this.flashMode, previewRequestBuilder);

                //    cameraDevice.createCaptureSession(Arrays.asList(surface, imageReader.getSurface()),
                //                new CameraCaptureSession.StateCallback()
                //                {



                //            public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession)
                //    {
                //        // The camera is already closed
                //        if (null == cameraDevice)
                //        {
                //            return;
                //        }
                //        captureSession = cameraCaptureSession;
                //        try
                //        {
                //            previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                //                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

                //            previewRequest = previewRequestBuilder.build();
                //            captureSession.setRepeatingRequest(previewRequest,
                //                    captureCallback, backgroundHandler);
                //        }
                //        catch (CameraAccessException e)
                //        {
                //            e.printStackTrace();
                //        }
                //    }


                //    public void onConfigureFailed(@NonNull CameraCaptureSession session)
                //    {
                //        Log.e("xx", "onConfigureFailed" + session);
                //    }
                //}, backgroundHandler);
            }
            catch (CameraAccessException e)
            {
                e.PrintStackTrace();
            }
        }
Пример #14
0
        private void OnScrollChanged()
        {
            if (_mCallbacks != null)
            {
                if (ChildCount > 0)
                {
                    int firstVisiblePosition = FirstVisiblePosition;
                    for (int i = FirstVisiblePosition, j = 0; i <= LastVisiblePosition; i++, j++)
                    {
                        if (_mChildrenHeights.IndexOfKey(i) < 0 || GetChildAt(j).Height != _mChildrenHeights.Get(i))
                        {
                            if (i % GetNumColumnsCompat() == 0)
                            {
                                _mChildrenHeights.Put(i, GetChildAt(j).Height);
                            }
                        }
                    }

                    View firstVisibleChild = GetChildAt(0);
                    if (firstVisibleChild != null)
                    {
                        if (_mPrevFirstVisiblePosition < firstVisiblePosition)
                        {
                            // scroll down
                            int skippedChildrenHeight = 0;
                            if (firstVisiblePosition - _mPrevFirstVisiblePosition != 1)
                            {
                                for (int i = firstVisiblePosition - 1; i > _mPrevFirstVisiblePosition; i--)
                                {
                                    if (0 < _mChildrenHeights.IndexOfKey(i))
                                    {
                                        skippedChildrenHeight += _mChildrenHeights.Get(i);
                                    }
                                }
                            }
                            _mPrevScrolledChildrenHeight += _mPrevFirstVisibleChildHeight + skippedChildrenHeight;
                            _mPrevFirstVisibleChildHeight = firstVisibleChild.Height;
                        }
                        else if (firstVisiblePosition < _mPrevFirstVisiblePosition)
                        {
                            // scroll up
                            int skippedChildrenHeight = 0;
                            if (_mPrevFirstVisiblePosition - firstVisiblePosition != 1)
                            {
                                for (int i = _mPrevFirstVisiblePosition - 1; i > firstVisiblePosition; i--)
                                {
                                    if (0 < _mChildrenHeights.IndexOfKey(i))
                                    {
                                        skippedChildrenHeight += _mChildrenHeights.Get(i);
                                    }
                                }
                            }
                            _mPrevScrolledChildrenHeight -= firstVisibleChild.Height + skippedChildrenHeight;
                            _mPrevFirstVisibleChildHeight = firstVisibleChild.Height;
                        }
                        else if (firstVisiblePosition == 0)
                        {
                            _mPrevFirstVisibleChildHeight = firstVisibleChild.Height;
                        }
                        if (_mPrevFirstVisibleChildHeight < 0)
                        {
                            _mPrevFirstVisibleChildHeight = 0;
                        }
                        _mScrollY = _mPrevScrolledChildrenHeight - firstVisibleChild.Top;
                        _mPrevFirstVisiblePosition = firstVisiblePosition;

                        _mCallbacks.OnScrollChanged(_mScrollY, _mFirstScroll, _mDragging);
                        if (_mFirstScroll)
                        {
                            _mFirstScroll = false;
                        }

                        if (_mPrevScrollY < _mScrollY)
                        {
                            _mScrollState = ObservableScrollState.Up;
                        }
                        else if (_mScrollY < _mPrevScrollY)
                        {
                            _mScrollState = ObservableScrollState.Down;
                        }
                        else
                        {
                            _mScrollState = ObservableScrollState.Stop;
                        }
                        _mPrevScrollY = _mScrollY;
                    }
                }
            }
        }
        /// <summary>
        /// Takes a picture.
        /// </summary>
        private void TakePicture()
        {
            try
            {
                Activity activity = Activity;
                if (activity == null || mCameraDevice == null)
                {
                    return;
                }
                CameraManager manager = (CameraManager)activity.GetSystemService(Context.CameraService);

                // Pick the best JPEG size that can be captures with this CameraDevice
                CameraCharacteristics characteristics = manager.GetCameraCharacteristics(mCameraDevice.Id);
                Size[] jpegSizes = null;
                if (characteristics != null)
                {
                    jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);
                }
                int width  = 640;
                int height = 480;
                if (jpegSizes != null && jpegSizes.Length > 0)
                {
                    width  = jpegSizes[0].Width;
                    height = jpegSizes[0].Height;
                }

                // We use an ImageReader to get a JPEG from CameraDevice
                // Here, we create a new ImageReader and prepare its Surface as an output from the camera
                ImageReader    reader         = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1);
                List <Surface> outputSurfaces = new List <Surface>(2);
                outputSurfaces.Add(reader.Surface);
                outputSurfaces.Add(new Surface(mTextureView.SurfaceTexture));

                CaptureRequest.Builder captureBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
                captureBuilder.AddTarget(reader.Surface);
                SetUpCaptureRequestBuilder(captureBuilder);
                // Orientation
                SurfaceOrientation rotation = activity.WindowManager.DefaultDisplay.Rotation;
                captureBuilder.Set(CaptureRequest.JpegOrientation, new Java.Lang.Integer(ORIENTATIONS.Get((int)rotation)));

                // Output file
                File file = new File(activity.GetExternalFilesDir(null), "pic.jpg");

                // This listener is called when an image is ready in ImageReader
                // Right click on ImageAvailableListener in your IDE and go to its definition
                ImageAvailableListener readerListener = new ImageAvailableListener()
                {
                    File = file
                };

                // We create a Handler since we want to handle the resulting JPEG in a background thread
                HandlerThread thread = new HandlerThread("CameraPicture");
                thread.Start();
                Handler backgroundHandler = new Handler(thread.Looper);
                reader.SetOnImageAvailableListener(readerListener, backgroundHandler);

                //This listener is called when the capture is completed
                // Note that the JPEG data is not available in this listener, but in the ImageAvailableListener we created above
                // Right click on CameraCaptureListener in your IDE and go to its definition
                CameraCaptureListener captureListener = new CameraCaptureListener()
                {
                    Fragment = this, File = file
                };

                mCameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener()
                {
                    OnConfiguredAction = (CameraCaptureSession session) => {
                        try
                        {
                            session.Capture(captureBuilder.Build(), captureListener, backgroundHandler);
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
                        }
                    }
                }, backgroundHandler);
            }
            catch (Exception ex) {
                Log.WriteLine(LogPriority.Info, "Taking picture error: ", ex.StackTrace);
            }
        }