private async Task InitializeCameraAsync(DeviceInformation preferredDevice) { try { // if (_mediaCapture == null) //{ Debug.WriteLine("open device"); // Get the camera devices try { // Create MediaCapture _mediaCapture = new MediaCapture(); // Initialize MediaCapture and settings await _mediaCapture.InitializeAsync( new MediaCaptureInitializationSettings { VideoDeviceId = preferredDevice.Id }); // Handle camera device location if (preferredDevice.EnclosureLocation == null || preferredDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown) { Debug.WriteLine("null"); _externalCamera = true; } else { _externalCamera = false; _mirroringPreview = (preferredDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front); } // ShowMessage(preferredDevice.EnclosureLocation.ToString()); _rotationHelper = new CameraRotationHelper(preferredDevice.EnclosureLocation); _rotationHelper.OrientationChanged += RotationHelper_OrientationChanged; _mediaCapture.GetPreviewRotation(); // Set the preview source for the CaptureElement PreviewControl.Visibility = Visibility.Visible; PreviewControl.Source = _mediaCapture; PreviewControl.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; // popUpDisplayText1.Text = "Let's take a picture! Smile~"; // Start viewing through the CaptureElement await _mediaCapture.StartPreviewAsync(); await SetPreviewRotationAsync(); } catch (Exception e) { ShowMessage(e.ToString()); } // } } catch (UnauthorizedAccessException Error) { ShowMessage(Error.ToString()); } }
/// <summary> /// control the camera frame invert , flip to the mirror image /// </summary> private async Task SetPreviewRotationAsync() { if (!_externalCamera) { // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames var rotation = _rotationHelper.GetCameraPreviewOrientation(); var props = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview); Guid RotationKey = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1"); props.Properties.Add(RotationKey, CameraRotationHelper.ConvertSimpleOrientationToClockwiseDegrees(rotation)); await _mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, null); } }
private async void RotationHelper_OrientationChanged(object sender, bool updatePreview) { if (updatePreview) { await SetPreviewRotationAsync(); } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Rotate the buttons in the UI to match the rotation of the device var angle = CameraRotationHelper.ConvertSimpleOrientationToClockwiseDegrees(_rotationHelper.GetUIOrientation()); var transform = new RotateTransform { Angle = angle }; // The RenderTransform is safe to use (i.e. it won't cause layout issues) in this case, because these buttons have a 1:1 aspect ratio //CapturePhotoButton.RenderTransform = transform; //CapturePhotoButton.RenderTransform = transform; }); }