/// <summary> /// Initializes a new DetectorVideoSink. /// </summary> /// <param name="detector">The CaptureSourceMarkerDetector to use.</param> public UWPMediaSink(CaptureSourceMarkerDetector detector) { this.detector = detector; listener.ConnectionReceived += Listener_ConnectionReceived; displayOrientation = displayInformation.CurrentOrientation; displayInformation.OrientationChanged += DisplayInformation_OrientationChanged; }
protected async override void OnNavigatedTo(NavigationEventArgs e) { _dataTransferManager = DataTransferManager.GetForCurrentView(); _dataTransferManager.DataRequested += OnDataRequested; _navigationHelper.OnNavigatedTo(e); if (InstagramModel != null) { await InstagramModel.LoadItemsAsync(); InstagramModel.SelectItem(e.Parameter); InstagramModel.ViewType = ViewTypes.Detail; } DataContext = this; // Allow this page to rotate _currentOrientations = DisplayInformation.AutoRotationPreferences; DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait | DisplayOrientations.Landscape | DisplayOrientations.LandscapeFlipped | DisplayOrientations.PortraitFlipped; // Handle orientation changes DisplayInformation.GetForCurrentView().OrientationChanged += this.OnOrientationChanged; this.TransitionStoryboardState(); }
private void DisplayInformation_OrientationChanged(DisplayInformation sender, Object args) { displayOrientation = sender.CurrentOrientation; if (capturing) { setPreviewRotation(); } }
public CameraCaptureUIPage() { previous = DisplayInformation.AutoRotationPreferences; DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape; this.Loaded += CameraCaptureUIPage_Loaded; this.Unloaded += CameraCaptureUIPage_Unloaded; this.InitializeComponent(); }
protected override void OnNavigatedTo(NavigationEventArgs e) { this.currentDisplayOrientations = DisplayInformation.AutoRotationPreferences; DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait; string id = e.Parameter as string; this.OpenScript(id); base.OnNavigatedTo(e); }
private async void PageLoaded(object sender, RoutedEventArgs e) { _displayOrientation = _displayInformation.CurrentOrientation; await InitializeCameraAsync(); StorageFile sf = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///wordlist.txt", UriKind.Absolute)); var _words = await FileIO.ReadLinesAsync(sf); propertySet["tolerance"] = 0.78; propertySet["hue"] = 320; propertySet["dictionary"] = _words; await _mediaCapture.AddVideoEffectAsync(new VideoEffectDefinition(typeof(TresholdVideoEffect).FullName, propertySet), MediaStreamType.VideoPreview); var timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(400) }; var textblockes = new List<TextBlock>(); timer.Tick += (s, agrs) => { List<Point> centers = new List<Point>(); if (propertySet.ContainsKey("result")) Result.Text = propertySet["result"].ToString(); if (propertySet.ContainsKey("centers")) centers = propertySet["centers"] as List<Point>; centers = centers.ToList(); if (!centers.Any()) return; if (textblockes.Count == centers.Count) { for (int i = 0; i < centers.Count; i++) { textblockes[i].Margin = new Thickness(0, centers[i].Y, centers[i].X, 0); } } else { foreach(TextBlock text in textblockes) { canvas.Children.Remove(text); } textblockes.Clear(); for (int i = 0; i < centers.Count; i++) { var textblock = new TextBlock { Text = i.ToString(), Foreground = new SolidColorBrush(Colors.White), FontSize = 24, Margin = new Thickness(0, centers[i].Y, centers[i].X, 0) }; canvas.Children.Add(textblock); textblockes.Add(textblock); } } }; timer.Start(); }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { _autoRotation = DisplayInformation.AutoRotationPreferences; DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape; // TODO: Prepare page for display here. await InitializeAsync(); // TODO: If your application contains multiple pages, ensure that you are // handling the hardware Back button by registering for the // Windows.Phone.UI.Input.HardwareButtons.BackPressed event. // If you are using the NavigationHelper provided by some templates, // this event is handled for you. }
private static int ConvertDisplayOrientationToDegrees(DisplayOrientations orientation) { switch (orientation) { case DisplayOrientations.Portrait: return 90; case DisplayOrientations.LandscapeFlipped: return 180; case DisplayOrientations.PortraitFlipped: return 270; case DisplayOrientations.Landscape: default: return 0; } }
protected override void OnNavigatedTo(NavigationEventArgs e) { LoadState(e.Parameter); if (HasPortrait) { _currentOrientations = DisplayInformation.AutoRotationPreferences; DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait | DisplayOrientations.Landscape | DisplayOrientations.LandscapeFlipped | DisplayOrientations.PortraitFlipped; // Handle orientation changes DisplayInformation.GetForCurrentView().OrientationChanged += this.OnOrientationChanged; this.TransitionStoryboardState(); } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { _dataTransferManager = DataTransferManager.GetForCurrentView(); _dataTransferManager.DataRequested += OnDataRequested; _navigationHelper.OnNavigatedTo(e); if (YouTubeChannelModel != null) { await YouTubeChannelModel.LoadItemsAsync(); YouTubeChannelModel.SelectItem(e.Parameter); YouTubeChannelModel.ViewType = ViewTypes.Detail; } ytViewer.OnNavigatedTo(); // Allow this page to rotate _currentOrientations = DisplayInformation.AutoRotationPreferences; DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait | DisplayOrientations.Landscape | DisplayOrientations.LandscapeFlipped | DisplayOrientations.PortraitFlipped; }
private async void OnDisplayInformationOrientationChanged(DisplayInformation sender, object args) { m_displayOrientation = sender.CurrentOrientation; await SetPreviewRotationAsync(); }
public static bool IsLandscape(this DisplayOrientations pageOrientation) { return((pageOrientation & DisplayOrientations.Landscape) != 0 || (pageOrientation & DisplayOrientations.LandscapeFlipped) != 0); }
void SetDisplayOrientationText(DisplayOrientations displayOrientation) { displayOrientationTextBlock.Text = displayOrientation.ToString(); }
private async void ajustes() { var qualifiers = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().QualifierValues; deviceFamily = qualifiers["DeviceFamily"]; double Width = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBounds.Width; double Height = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBounds.Height; _displayOrientation = _displayInformation.CurrentOrientation; if (_orientationSensor != null) { _deviceOrientation = _orientationSensor.GetCurrentOrientation(); } if (deviceFamily == "Mobile") { //Content.Visibility = Visibility.Collapsed; MainGrid.ColumnDefinitions[0].Width = new GridLength(1577 + 723); MainGrid.ColumnDefinitions[1].Width = new GridLength(0); MainGrid.RowDefinitions[0].Height = new GridLength(1106); MainGrid.RowDefinitions[1].Height = new GridLength(2990); Page.SetValue(Grid.ColumnProperty, 0); Page.SetValue(Grid.RowProperty, 1); Page.Margin = new Thickness(Width * 0.026); age_genre.FontSize = 80; age_genre.Foreground = new SolidColorBrush(Colors.White); } else { //MainGrid.ColumnDefinitions[0].Width = new GridLength(Width * 0.27); //MainGrid.ColumnDefinitions[1].Width = new GridLength(Width * 0.72); //MainGrid.RowDefinitions[0].Height = new GridLength(Height * 0.27); //MainGrid.RowDefinitions[1].Height = new GridLength(Height * 0.72); //GridLength minWidth = new GridLength(300); //GridLength mg = MainGrid.ColumnDefinitions[0].Width; //if (mg.Value < minWidth.Value) //{ // MainGrid.ColumnDefinitions[0].Width = minWidth; // HoldCamera.Margin = new Thickness(300 * 0.026); // LeftPanel.Margin = new Thickness(300 * 0.026); //} //HoldCamera.Margin = new Thickness(Width * 0.026); //LeftPanel.Margin = new Thickness(Width * 0.026); //ProductImage.Margin = new Thickness(Width * 0.026); //Content.Margin = new Thickness(Width * 0.026); //ProductName.Margin = new Thickness(Width * 0.015625, Height * 0.027777, Width * 0.15625, Height * 0.925925); //Price.Margin = new Thickness(Width * 0.3125, Height * 0.027777, Width * 0.015625, Height * 0.185185); //logoStore.Margin = new Thickness(Width * 0.3125, Height * 0.185185, Width * 0.015625, Height * 0.027777); } RegisterEventHandlers(); await InitContiniousRecognition(); }
private async void DisplayInformation_OrientationChanged(DisplayInformation sender, object args) { _displayOrientation = sender.CurrentOrientation; if (_isPreviewing) { await SetPreviewRotationAsync(); } }
private void UpdateVisibility(DisplayOrientations orientation) { if (HideOnLandscape) { if (orientation == Windows.Graphics.Display.DisplayOrientations.Landscape || orientation == Windows.Graphics.Display.DisplayOrientations.LandscapeFlipped) { this.Visibility = Visibility.Collapsed; } else if (orientation == Windows.Graphics.Display.DisplayOrientations.Portrait || orientation == Windows.Graphics.Display.DisplayOrientations.PortraitFlipped) { this.Visibility = Visibility.Visible; } } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { // Populate orientation variables with the current state and register for future changes _displayOrientation = _displayInformation.CurrentOrientation; _displayInformation.OrientationChanged += DisplayInformation_OrientationChanged; await InitializeCameraAsync(); }
/// <summary> /// Attempts to lock the page orientation, hide the StatusBar (on Phone) and registers event handlers for hardware buttons and orientation sensors /// </summary> /// <returns></returns> private async Task SetupUiAsync() { // Attempt to lock page to landscape orientation to prevent the CaptureElement from rotating, as this gives a better experience DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape; // Hide the status bar if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar")) { await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync(); } // Populate orientation variables with the current state _displayOrientation = _displayInformation.CurrentOrientation; if (_orientationSensor != null) { _deviceOrientation = _orientationSensor.GetCurrentOrientation(); } RegisterEventHandlers(); var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); // Fall back to the local app storage if the Pictures Library is not available _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder; }
public void DisplayOrientationChanged(DisplayOrientations orientation) { InvokeHubChannel <IVoipChannel>(orientation); }
void OnAppResuming(object sender, object o) { _displayOrientation = _displayInformation.CurrentOrientation; _displayInformation.OrientationChanged += OnOrientationChanged; }
public IAsyncAction DisplayOrientationChangedAsync(DisplayOrientations orientation) { RtcManager.Instance.DisplayOrientation = orientation; return(Task.CompletedTask.AsAsyncAction()); }
private void DisplayInformation_OrientationChanged(DisplayInformation sender, object args) { _displayOrientation = sender.CurrentOrientation; }
public IAsyncAction DisplayOrientationChangedAsync(DisplayOrientations orientation) { return(InvokeHubChannelAsync <ICallChannel>(orientation).AsTask().AsAsyncAction()); }
static partial void SetOrientationPartial(DisplayOrientations orientations);
async void SetupCamera() { _displayOrientation = _displayInformation.CurrentOrientation; _displayInformation.OrientationChanged += OnOrientationChanged; await InitializeCameraAsync(); }
/// <summary> /// Attempts to lock the page orientation, hide the StatusBar (on Phone) and registers event handlers for hardware buttons and orientation sensors /// </summary> /// <returns></returns> private async Task SetupUiAsync() { // Hide the status bar if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar")) { await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync(); } // Populate orientation variables with the current state _displayOrientation = _displayInformation.CurrentOrientation; if (_orientationSensor != null) { _deviceOrientation = _orientationSensor.GetCurrentOrientation(); } RegisterEventHandlers(); var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); // Fall back to the local app storage if the Pictures Library is not available _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder; }
/// <summary> /// finds the degree of rotation to rotate the image/video preview /// </summary> /// <param name="displayOrientation"></param> /// the current phone orientation /// <param name="counterclockwise"></param> /// checks if rotation should be done clockwise or counterclockwise /// <returns></returns> private VideoRotation VideoRotationLookup(DisplayOrientations displayOrientation, bool counterclockwise) { switch (displayOrientation) { case DisplayOrientations.Landscape: return VideoRotation.None; case DisplayOrientations.Portrait: return (counterclockwise) ? VideoRotation.Clockwise270Degrees : VideoRotation.Clockwise90Degrees; case DisplayOrientations.LandscapeFlipped: return VideoRotation.Clockwise180Degrees; case DisplayOrientations.PortraitFlipped: return (counterclockwise) ? VideoRotation.Clockwise90Degrees : VideoRotation.Clockwise270Degrees; default: return VideoRotation.None; } }
private SimpleOrientation ConvertDisplayOrientationToSimpleOrientation(DisplayOrientations orientation) { SimpleOrientation result; switch (orientation) { case DisplayOrientations.Landscape: result = SimpleOrientation.NotRotated; break; case DisplayOrientations.PortraitFlipped: result = SimpleOrientation.Rotated90DegreesCounterclockwise; break; case DisplayOrientations.LandscapeFlipped: result = SimpleOrientation.Rotated180DegreesCounterclockwise; break; case DisplayOrientations.Portrait: default: result = SimpleOrientation.Rotated270DegreesCounterclockwise; break; } // Above assumes landscape; offset is needed if native orientation is portrait if (_displayInformation.NativeOrientation == DisplayOrientations.Portrait) { result = AddOrientations(result, SimpleOrientation.Rotated90DegreesCounterclockwise); } return result; }
static DeviceOrientation GetDeviceOrientation(DisplayOrientations orientations) { switch (orientations) { case DisplayOrientations.Landscape: case DisplayOrientations.LandscapeFlipped: return DeviceOrientation.Landscape; case DisplayOrientations.Portrait: case DisplayOrientations.PortraitFlipped: return DeviceOrientation.Portrait; default: case DisplayOrientations.None: return DeviceOrientation.Other; } }
public App() { // save a pointer to ourself App.Current = this; InitializeComponent(); // app lifecycle event handlers EnteredBackground += OnEnteredBackground; Suspending += OnSuspending; Resuming += OnResuming; UnhandledException += OnUnhandledException; // we want full screen, but leave this off during dev ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.FullScreen; //ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.Auto; // we want landscape only DisplayOrientations orientations = DisplayOrientations.Landscape; DisplayInformation.AutoRotationPreferences = orientations; // Deferred execution until used. Check https://msdn.microsoft.com/library/dd642331(v=vs.110).aspx for further info on Lazy<T> class. _activationService = new Lazy <ActivationService>(CreateActivationService); // register our configuration service and initialize it SimpleIoc.Default.Register <ConfigurationService>(); ConfigurationService configurationService = (ConfigurationService)SimpleIoc.Default.GetInstance <ConfigurationService>(); if (null != configurationService) { // run this synchronously AsyncHelper.RunSync(() => configurationService.Initialize()); } // register our localization service and initialize it SimpleIoc.Default.Register <LocalizationService>(); LocalizationService localizationService = (LocalizationService)SimpleIoc.Default.GetInstance <LocalizationService>(); if (null != localizationService) { // async here might lead to a race condition, but no signs so far //localizationService.Initialize(); AsyncHelper.RunSync(() => localizationService.Initialize()); } // initialize the telemetry service SimpleIoc.Default.Register <TelemetryService>(); TelemetryService telemetryService = (TelemetryService)SimpleIoc.Default.GetInstance <TelemetryService>(); if (null != telemetryService) { if (null != configurationService) { // DO NOT try to run this asynchronously; MetroLog hangs when invoked async //AsyncHelper.RunSync(() => telemetryService.Initialize(configurationService.Configuration.TelemetryKey)); telemetryService.Initialize(configurationService.Configuration.IsTelemetryEnabled, configurationService.Configuration.TelemetryKey); // log app start TelemetryService.Current?.LogTelemetryEvent(TelemetryEvents.StartApplication); } } }
/// <summary> /// Calculates the size and location of the rectangle that contains the preview stream within the preview control, when the scaling mode is Uniform /// </summary> /// <param name="previewResolution">The resolution at which the preview is running</param> /// <param name="previewControl">The control that is displaying the preview using Uniform as the scaling mode</param> /// <param name="displayOrientation">The orientation of the display, to account for device rotation and changing of the CaptureElement display ratio compared to the camera stream</param> /// <returns></returns> public static Rect GetPreviewStreamRectInControl(VideoEncodingProperties previewResolution, CaptureElement previewControl, DisplayOrientations displayOrientation) { var result = new Rect(); // In case this function is called before everything is initialized correctly, return an empty result if (previewControl == null || previewControl.ActualHeight < 1 || previewControl.ActualWidth < 1 || previewResolution == null || previewResolution.Height == 0 || previewResolution.Width == 0) { return(result); } var streamWidth = previewResolution.Width; var streamHeight = previewResolution.Height; // For portrait orientations, the width and height need to be swapped if (displayOrientation == DisplayOrientations.Portrait || displayOrientation == DisplayOrientations.PortraitFlipped) { streamWidth = previewResolution.Height; streamHeight = previewResolution.Width; } // Start by assuming the preview display area in the control spans the entire width and height both (this is corrected in the next if for the necessary dimension) result.Width = previewControl.ActualWidth; result.Height = previewControl.ActualHeight; // If UI is "wider" than preview, letterboxing will be on the sides if ((previewControl.ActualWidth / previewControl.ActualHeight > streamWidth / (double)streamHeight)) { var scale = previewControl.ActualHeight / streamHeight; var scaledWidth = streamWidth * scale; result.X = (previewControl.ActualWidth - scaledWidth) / 2.0; result.Width = scaledWidth; } else // Preview stream is "wider" than UI, so letterboxing will be on the top+bottom { var scale = previewControl.ActualWidth / streamWidth; var scaledHeight = streamHeight * scale; result.Y = (previewControl.ActualHeight - scaledHeight) / 2.0; result.Height = scaledHeight; } return(result); }
/// <summary> /// Attempts to lock the page orientation, hide the StatusBar (on Phone) and registers event handlers for hardware buttons and orientation sensors /// </summary> /// <returns></returns> private async Task SetupUiAsync() { // Hide the status bar if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar")) { await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync(); } // Populate orientation variables with the current state _displayOrientation = _displayInformation.CurrentOrientation; if (_orientationSensor != null) { _deviceOrientation = _orientationSensor.GetCurrentOrientation(); } RegisterEventHandlers(); }
private async void Application_Resuming(object sender, object o) { // Handle global application events only if this page is active if (Frame.CurrentSourcePageType == typeof(MainPage)) { // Populate orientation variables with the current state and register for future changes _displayOrientation = _displayInformation.CurrentOrientation; _displayInformation.OrientationChanged += DisplayInformation_OrientationChanged; await InitializeCameraAsync(); } }
private static DisplayOrientation ToOrientation(DisplayOrientations orientations) { var result = DisplayOrientation.Default; if ((orientations & DisplayOrientations.Landscape) != 0) result |= DisplayOrientation.LandscapeLeft; if ((orientations & DisplayOrientations.LandscapeFlipped) != 0) result |= DisplayOrientation.LandscapeRight; if ((orientations & DisplayOrientations.Portrait) != 0) result |= DisplayOrientation.Portrait; if ((orientations & DisplayOrientations.PortraitFlipped) != 0) result |= DisplayOrientation.PortraitDown; return result; }
private async Task StartPreviewAsync() { // Prevent the device from sleeping while the preview is running _displayRequest.RequestActive(); // Set the preview source in the UI and mirror it if necessary HoldCamera.Source = mc; HoldCamera.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; // Start the preview try { await mc.StartPreviewAsync(); _isPreviewing = true; _previewProperties = mc.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview); } catch (Exception ex) { Debug.WriteLine("Exception when starting the preview: {0}", ex.ToString()); } // Initialize the preview to the current orientation if (_previewProperties != null) { _displayOrientation = _displayInformation.CurrentOrientation; await SetPreviewRotationAsync(); } }
/// <summary> /// This event will fire when the page is rotated, when the DisplayInformation.AutoRotationPreferences value set in the SetupUiAsync() method cannot be not honored. /// </summary> /// <param name="sender">The event source.</param> /// <param name="args">The event data.</param> private async void DisplayInformation_OrientationChanged(DisplayInformation sender, object args) { _displayOrientation = sender.CurrentOrientation; if (_isPreviewing) { await SetPreviewRotationAsync(); } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateButtonOrientation()); }
/// <summary> /// Gets a value that indicates if the aspect ratio is changing as part of the orientation change. /// </summary> /// <param name="oldOrientation"> /// The old orientation. /// </param> /// <param name="newOrientation"> /// The new orientation. /// </param> /// <returns> /// <c>true</c> if the aspect ratio is changing as part of the orientation change; otherwise <c>false</c>. /// </returns> public static bool IsAspectChanging(DisplayOrientations oldOrientation, DisplayOrientations newOrientation) { // Going from landscape to portrait? if ((oldOrientation == DisplayOrientations.Landscape) || (oldOrientation == DisplayOrientations.LandscapeFlipped)) { if ((newOrientation == DisplayOrientations.Portrait) || (newOrientation == DisplayOrientations.PortraitFlipped)) { return true; } } // Going from portrait to landscape? if ((oldOrientation == DisplayOrientations.Portrait) || (oldOrientation == DisplayOrientations.PortraitFlipped)) { if ((newOrientation == DisplayOrientations.Landscape) || (newOrientation == DisplayOrientations.LandscapeFlipped)) { return true; } } // Nope return false; }
public static bool IsPortrait(this DisplayOrientations pageOrientation) { return((pageOrientation & DisplayOrientations.Portrait) != 0 || (pageOrientation & DisplayOrientations.PortraitFlipped) != 0); }
/// <summary> /// Calculates the size and location of the rectangle that contains the preview stream within the preview control, when the scaling mode is Uniform /// </summary> /// <param name="previewResolution">The resolution at which the preview is running</param> /// <param name="previewControl">The control that is displaying the preview using Uniform as the scaling mode</param> /// <param name="displayOrientation">The orientation of the display, to account for device rotation and changing of the CaptureElement display ratio compared to the camera stream</param> /// <returns></returns> public static Rect GetPreviewStreamRectInControl(VideoEncodingProperties previewResolution, CaptureElement previewControl, DisplayOrientations displayOrientation) { var result = new Rect(); // In case this function is called before everything is initialized correctly, return an empty result if (previewControl == null || previewControl.ActualHeight < 1 || previewControl.ActualWidth < 1 || previewResolution == null || previewResolution.Height == 0 || previewResolution.Width == 0) { return result; } var streamWidth = previewResolution.Width; var streamHeight = previewResolution.Height; // For portrait orientations, the width and height need to be swapped if (displayOrientation == DisplayOrientations.Portrait || displayOrientation == DisplayOrientations.PortraitFlipped) { streamWidth = previewResolution.Height; streamHeight = previewResolution.Width; } // Start by assuming the preview display area in the control spans the entire width and height both (this is corrected in the next if for the necessary dimension) result.Width = previewControl.ActualWidth; result.Height = previewControl.ActualHeight; // If UI is "wider" than preview, letterboxing will be on the sides if ((previewControl.ActualWidth / previewControl.ActualHeight > streamWidth / (double)streamHeight)) { var scale = previewControl.ActualHeight / streamHeight; var scaledWidth = streamWidth * scale; result.X = (previewControl.ActualWidth - scaledWidth) / 2.0; result.Width = scaledWidth; } else // Preview stream is "wider" than UI, so letterboxing will be on the top+bottom { var scale = previewControl.ActualWidth / streamWidth; var scaledHeight = streamHeight * scale; result.Y = (previewControl.ActualHeight - scaledHeight) / 2.0; result.Height = scaledHeight; } return result; }
private async void DisplayInformation_OrientationChanged(DisplayInformation sender, object args) { _displayOrientation = sender.CurrentOrientation; await SetPreviewRotationAsync(); }
/// <summary> /// Starts the preview and adjusts it for for rotation and mirroring after making a request to keep the screen on /// </summary> /// <returns></returns> private async Task StartPreviewAsync() { // Prevent the device from sleeping while the preview is running _displayRequest.RequestActive(); // Set the preview source in the UI and mirror it if necessary PreviewControl.Source = _mediaCapture; PreviewControl.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; // Start the preview await _mediaCapture.StartPreviewAsync(); _previewProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview); // Initialize the preview to the current orientation if (_previewProperties != null) { _displayOrientation = _displayInformation.CurrentOrientation; await SetPreviewRotationAsync(); } }
private async Task StartPreviewAsync() { try { m_mediaCapture = new MediaCapture(); m_mediaCapture.Failed += OnMediaCaptureFailed; _displayRequest.RequestActive(); // Populate orientation variables with the current state m_displayOrientation = m_displayInformation.CurrentOrientation; RegisterEventHandlers(); var devInfo = await FindCameraDeviceByPanelAsync(m_desiredCameraPanel); var id = devInfo != null ? devInfo.Id : string.Empty; var settings = new MediaCaptureInitializationSettings(); settings.VideoDeviceId = id; settings.MediaCategory = MediaCategory.Communications; await m_mediaCapture.InitializeAsync(settings); m_mediaCapture.SetEncoderProperty(MediaStreamType.VideoPreview, new Guid("9C27891A-ED7A-40e1-88E8-B22727A024EE"), PropertyValue.CreateUInt32(1)); var resolutionMax = GetHighestResolution(); ImageWidth = resolutionMax.Width; ImageHeight = resolutionMax.Height; await m_mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync (MediaStreamType.VideoPreview, resolutionMax); m_PreviewVideoElement.Source = m_mediaCapture; await AddEffectsAsync(); await m_mediaCapture.StartPreviewAsync(); await SetPreviewRotationAsync(); IsCaptureEnabled = true; UpdateButtonState(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
/// <summary> /// Attempts to lock the page orientation, hide the StatusBar (on Phone) and registers event handlers for hardware buttons and orientation sensors /// </summary> /// <returns></returns> private async Task SetupUiAsync() { // Attempt to lock page to landscape orientation to prevent the CaptureElement from rotating, as this gives a better experience DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape; // Hide the status bar if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar")) { await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync(); } // Populate orientation variables with the current state _displayOrientation = _displayInformation.CurrentOrientation; if (_orientationSensor != null) { _deviceOrientation = _orientationSensor.GetCurrentOrientation(); } RegisterEventHandlers(); }
public async Task InitCameraAsync(string cameraName, double screenRatio) { try { Cleanup(); Status = "Initializing camera to capture audio and video..."; VideoCapture = new MediaCapture(); MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings() { StreamingCaptureMode = StreamingCaptureMode.Video }; var allCameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); var selectedCamera = allCameras.FirstOrDefault(c => c.Name == cameraName); if (selectedCamera != null) { settings.VideoDeviceId = selectedCamera.Id; } await VideoCapture.InitializeAsync(settings); // Set callbacks for failure and recording limit exceeded Status = "Device successfully initialized for video recording!"; VideoCapture.Failed += mediaCapture_Failed; // Start Preview PreviewControl.Source = VideoCapture; PreviewControl.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; // Also mirror the canvas if the preview is being mirrored FacesCanvas.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; // Query all properties of the specified stream type var props = VideoCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview); IEnumerable <StreamResolution> allStreamProperties = props.Select(x => new StreamResolution(x)); // Order them by resolution then frame rate allStreamProperties = allStreamProperties.Where(p => p.AspectRatio == screenRatio).OrderByDescending(x => x.FrameRate).ThenByDescending(x => x.Height * x.Width); await VideoCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, allStreamProperties.First().EncodingProperties); await VideoCapture.StartPreviewAsync(); _previewProperties = VideoCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; // Initialize the preview to the current orientation if (_previewProperties != null) { _displayOrientation = _displayInformation.CurrentOrientation; } _isPreviewing = true; Status = "Camera preview succeeded"; await InitFaceTrackerAsync(); _faceTracker = await FaceTracker.CreateAsync(); } catch (Exception ex) { Status = "Unable to initialize camera for audio/video mode: " + ex.Message; } }