Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
Importante
Asegúrese de que tiene habilitada la funcionalidad de webcam para que la aplicación acceda a la cámara del dispositivo.
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Page x:Class="CameraPreviewExperiment.Samples.CameraPreviewSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:CommunityToolkit.WinUI.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:CameraPreviewExperiment.Samples"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
mc:Ignorable="d">
<StackPanel HorizontalAlignment="Center"
Orientation="Vertical"
Spacing="12">
<Button HorizontalAlignment="Center"
Click="CaptureButton_Click"
Content="Capture"
Style="{StaticResource AccentButtonStyle}" />
<controls:CameraPreview x:Name="CameraPreviewControl"
Height="320"
IsFrameSourceGroupButtonVisible="{x:Bind ShowCamera, Mode=OneWay}" />
<muxc:InfoBar x:Name="ErrorBar"
Title="Error"
IsOpen="False"
Severity="Error" />
<Image x:Name="CurrentFrameImage"
Height="120"
HorizontalAlignment="Center" />
</StackPanel>
</Page>
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using CommunityToolkit.WinUI.Controls;
using CommunityToolkit.WinUI.Helpers;
using Windows.Graphics.Imaging;
using Windows.Media;
using Windows.ApplicationModel;
#if WINAPPSDK
using Microsoft.UI.Xaml.Media.Imaging;
#else
using Windows.UI.Xaml.Media.Imaging;
#endif
namespace CameraPreviewExperiment.Samples;
[ToolkitSampleBoolOption("ShowCamera", true, Title = "Show camera toggle button")]
[ToolkitSample(id: nameof(CameraPreviewSample), "CameraPreview", description: $"A sample for showing how to create and use a {nameof(CameraPreview)} control.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "Controls dispose resources when unloaded")]
public sealed partial class CameraPreviewSample : Page
{
private static SemaphoreSlim? semaphoreSlim;
private VideoFrame _currentVideoFrame;
private SoftwareBitmapSource _softwareBitmapSource;
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public CameraPreviewSample()
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
{
this.InitializeComponent();
Loaded += this.CameraPreviewSample_Loaded;
Unloaded += this.CameraPreviewSample_Unloaded;
semaphoreSlim = new SemaphoreSlim(1);
}
private void CameraPreviewSample_Unloaded(object sender, RoutedEventArgs e)
{
Unloaded -= this.CameraPreviewSample_Unloaded;
_softwareBitmapSource?.Dispose();
}
private void CameraPreviewSample_Loaded(object sender, RoutedEventArgs e)
{
Loaded -= this.CameraPreviewSample_Loaded;
Load();
}
private async void Load()
{
// Using a semaphore lock for synchronization.
// This method gets called multiple times when accessing the page from Latest Pages
// and creates unused duplicate references to Camera and memory leaks.
await semaphoreSlim!.WaitAsync();
var cameraHelper = CameraPreviewControl?.CameraHelper;
UnsubscribeFromEvents();
if (CameraPreviewControl != null)
{
CameraPreviewControl.PreviewFailed += CameraPreviewControl_PreviewFailed!;
await CameraPreviewControl.StartAsync(cameraHelper!);
CameraPreviewControl.CameraHelper.FrameArrived += CameraPreviewControl_FrameArrived!;
}
_softwareBitmapSource = new SoftwareBitmapSource();
CurrentFrameImage.Source = _softwareBitmapSource;
semaphoreSlim.Release();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
#if !WINAPPSDK
Application.Current.Suspending += Application_Suspending;
Application.Current.Resuming += Application_Resuming;
#endif
}
protected async override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
#if !WINAPPSDK
Application.Current.Suspending -= Application_Suspending;
Application.Current.Resuming -= Application_Resuming;
#endif
await CleanUpAsync();
}
private async void Application_Suspending(object? sender, SuspendingEventArgs e)
{
if (Frame?.CurrentSourcePageType == typeof(CameraPreviewSample))
{
var deferral = e.SuspendingOperation.GetDeferral();
await CleanUpAsync();
deferral.Complete();
}
}
private async void Application_Resuming(object? sender, object e)
{
if (CameraPreviewControl != null)
{
var cameraHelper = CameraPreviewControl.CameraHelper;
CameraPreviewControl.PreviewFailed += CameraPreviewControl_PreviewFailed!;
await CameraPreviewControl.StartAsync(cameraHelper);
CameraPreviewControl.CameraHelper.FrameArrived += CameraPreviewControl_FrameArrived!;
}
}
private void CameraPreviewControl_FrameArrived(object? sender, FrameEventArgs e)
{
_currentVideoFrame = e.VideoFrame;
}
private void CameraPreviewControl_PreviewFailed(object? sender, PreviewFailedEventArgs e)
{
ErrorBar.Message = e.Error;
ErrorBar.IsOpen = true;
}
private async void CaptureButton_Click(object? sender, RoutedEventArgs e)
{
var softwareBitmap = _currentVideoFrame?.SoftwareBitmap;
if (softwareBitmap != null)
{
if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
{
softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
}
await _softwareBitmapSource!.SetBitmapAsync(softwareBitmap);
}
}
private void UnsubscribeFromEvents()
{
if (CameraPreviewControl.CameraHelper != null)
{
CameraPreviewControl.CameraHelper.FrameArrived -= CameraPreviewControl_FrameArrived!;
}
CameraPreviewControl.PreviewFailed -= CameraPreviewControl_PreviewFailed!;
}
private async Task CleanUpAsync()
{
UnsubscribeFromEvents();
CameraPreviewControl.Stop();
await CameraPreviewControl.CameraHelper.CleanUpAsync();
}
}
Sintaxis
<controls:CameraPreview x:Name="CameraPreviewControl"/>
CameraPreviewControl.PreviewFailed += CameraPreviewControl_PreviewFailed;
await CameraPreviewControl.StartAsync();
CameraPreviewControl.CameraHelper.FrameArrived += CameraPreviewControl_FrameArrived;
private void CameraPreviewControl_FrameArrived(object sender, FrameEventArgs e)
{
var videoFrame = e.VideoFrame;
var softwareBitmap = videoFrame.SoftwareBitmap;
}
private void CameraPreviewControl_PreviewFailed(object sender, PreviewFailedEventArgs e)
{
var errorMessage = e.Error;
}
Importante
Como desarrollador, deberá asegurarse de que los recursos de CameraHelper que usa el control se limpien cuando corresponda. Consulte la documentación de CameraHelper para obtener más detalles
Ejemplos
Muestra el uso del control de cámara y del asistente de la cámara para obtener fotogramas de vídeo de un grupo de origen de fotogramas multimedia específico.
var availableFrameSourceGroups = await CameraHelper.GetFrameSourceGroupsAsync();
if(availableFrameSourceGroups != null)
{
CameraHelper cameraHelper = new CameraHelper() { FrameSourceGroup = availableFrameSourceGroups.FirstOrDefault() };
_cameraPreviewControl.PreviewFailed += CameraPreviewControl_PreviewFailed;
await _cameraPreviewControl.StartAsync(cameraHelper);
_cameraPreviewControl.CameraHelper.FrameArrived += CameraPreviewControl_FrameArrived;
}
Windows Community Toolkit