Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The CameraView provides the ability to connect to a camera, display a preview from the camera, take photos, and record videos. The CameraView also offers features to support controlling the flash and torch, adjusting zoom, saving captured media to a file, and offering different hooks for events.
The following sections will incrementally build on how to use the CameraView in a .NET MAUI application. They rely on the use of a CameraViewModel that will be set as the BindingContext of the example CameraViewPage.
Platform specific initialization
The CameraView is part of the CommunityToolkit.Maui.Camera nuget package. To first use the CameraView please refer to the Getting started section. The following platform specific setup is required.
The following permissions need to be added to the Platforms/Android/AndroidManifest.xml file:
<uses-permission android:name="android.permission.CAMERA" />
In case you plan to record video, request Microphone permissions:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
This should be added inside the <manifest> element. Below shows a more complete example:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true" />
<uses-permission android:name="android.permission.CAMERA" />
<!--Optional. Only for video recording-->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
</manifest>
Basic usage
The CameraView can be added to a .NET MAUI application in the following way.
Request permissions
Developers must manually request Permissions.Camera and/or Permissions.Microphone:
var cameraPermissionsRequest = await Permissions.RequestAsync<Permissions.Camera>();
In case you plan to record video, request Microphone permissions:
var microphonePermissionsRequest = await Permissions.RequestAsync<Permissions.Microphone>();
Note
A CameraView connects to its camera and starts its preview when it is shown, which can be before your app has the camera permission, for example while your app is still asking for it. A start that fails because the app doesn't have the permission is reported through the ErrorOccurred event, and the preview stays stopped. On Android, the preview then starts by itself when the app resumes with the permission granted. On the other platforms, call StartCameraPreview again once the app has the permission. See Start preview for details.
Including the XAML namespace
In order to use the toolkit in XAML the following xmlns needs to be added into your page or view:
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
Therefore the following:
<ContentPage
x:Class="CommunityToolkit.Maui.Sample.Pages.MyPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
</ContentPage>
Would be modified to include the xmlns as follows:
<ContentPage
x:Class="CommunityToolkit.Maui.Sample.Pages.MyPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">
</ContentPage>
<ContentPage
x:Class="CommunityToolkit.Maui.Sample.Pages.CameraViewPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">
<Grid ColumnDefinitions="*,*,*" RowDefinitions="*,30">
<toolkit:CameraView
Grid.ColumnSpan="3"
Grid.Row="0" />
</Grid>
</ContentPage>
The result will be a surface rendering the output of the default camera connected to the device.
Access the current camera
The SelectedCamera property provides the ability to access the currently selected camera.
Changing SelectedCamera while the preview runs restarts the preview with the new camera. If the new camera can't be started, for example because another app is using it, the failure is reported through the ErrorOccurred event, and selecting another camera starts the preview with that camera. On Android, selecting another camera while a video recording runs doesn't end the recording: the change is applied when the recording is stopped or replaced. StopCameraPreview cancels a camera switch that is still waiting for the platform, see Cancel pending starts.
The following example shows how to bind the SelectedCamera property from the CameraView to a property on the CameraViewModel with the same name (SelectedCamera).
<ContentPage
x:Class="CommunityToolkit.Maui.Sample.Pages.CameraViewPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">
<Grid ColumnDefinitions="*,*,*" RowDefinitions="*,30,30">
<toolkit:CameraView
Grid.ColumnSpan="3"
Grid.Row="0"
SelectedCamera="{Binding SelectedCamera}" />
</Grid>
</ContentPage>
Control Zoom
The SelectedCamera property provides both a MinimumZoomFactor and a MaximumZoomFactor property, these are read-only and provide developers with a programmatic way of determining what zoom can be applied to the current camera. In order to change the zoom on the current camera the CameraView provides the ZoomFactor property.
Note
If a value is provided outside of the MinimumZoomFactor and MaximumZoomFactor the CameraView will clamp the value to keep it within the bounds.
Note
On Android, MinimumZoomFactor and MaximumZoomFactor come from CameraX for each camera, in Debug and in Release (trimmed) apps. Earlier versions reported a range of 1 to 1 for every camera in Release apps (#2389), which clamped every ZoomFactor to 1.
The following example shows how to add a Slider into the application and setup the following bindings:
- Bind the
Maximumproperty of theSliderto theMaximumZoomFactorof theSelectedCameraproperty. - Bind the
Minimumproperty of theSliderto theMinimumZoomFactorof theSelectedCameraproperty. - Bind the
Valueproperty of theSliderto theCurrentZoomproperty on theCameraViewModelclass.
The final change involves binding the ZoomFactor property of the CameraView to the CurrentZoom property on the CameraViewModel class.
<ContentPage
x:Class="CommunityToolkit.Maui.Sample.Pages.CameraViewPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">
<Grid ColumnDefinitions="*,*,*" RowDefinitions="*,30,30">
<toolkit:CameraView
Grid.ColumnSpan="3"
Grid.Row="0"
SelectedCamera="{Binding SelectedCamera}"
ZoomFactor="{Binding CurrentZoom}" />
<Slider
Grid.Column="0"
Grid.Row="1"
Value="{Binding CurrentZoom}"
Maximum="{Binding SelectedCamera.MaximumZoomFactor, FallbackValue=1}"
Minimum="{Binding SelectedCamera.MinimumZoomFactor, FallbackValue=1}"/>
</Grid>
</ContentPage>
Camera Flash Mode
The CameraView provides the ability to programmatically change the flash mode on the device, the possible options are:
Off- the flash is off and will not be used.On- the flash is on and will always be used.Auto- the flash will automatically be used based on the lighting conditions.
The SelectedCamera property also provides the IsFlashSupported which makes it possible to determine whether the currently selected camera has a flash that can be controlled.
The following example shows how to add a Picker into the application and setup the following bindings:
- Bind the
IsVisibleproperty of thePickerto theIsFlashSupportedof theSelectedCameraproperty. - Bind the
ItemsSourceproperty of thePickerto theFlashModesproperty on theCameraViewModelclass - a simple list of the possible values of theCameraFlashModeenum. - Bind the
SelectedItemproperty of thePickerto theFlashModeproperty on theCameraViewModelclass.
The final change involves binding the CameraFlashMode property of the CameraView to the FlashMode property on the CameraViewModel class.
<ContentPage
x:Class="CommunityToolkit.Maui.Sample.Pages.CameraViewPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">
<Grid ColumnDefinitions="*,*,*" RowDefinitions="*,30,30">
<toolkit:CameraView
Grid.ColumnSpan="3"
Grid.Row="0"
SelectedCamera="{Binding SelectedCamera}"
ZoomFactor="{Binding CurrentZoom}"
CameraFlashMode="{Binding FlashMode}" />
<Slider
Grid.Column="0"
Grid.Row="1"
Value="{Binding CurrentZoom}"
Maximum="{Binding SelectedCamera.MaximumZoomFactor, FallbackValue=1}"
Minimum="{Binding SelectedCamera.MinimumZoomFactor, FallbackValue=1}"/>
<Picker
Grid.Column="1"
Grid.Row="1"
Title="Flash"
IsVisible="{Binding Path=SelectedCamera.IsFlashSupported, FallbackValue=false}"
ItemsSource="{Binding FlashModes}"
SelectedItem="{Binding FlashMode}" />
</Grid>
</ContentPage>
ImageCaptureResolution
The CameraView provides the ability to programmatically change resolution for images captured from the current camera.
Note
This will not change the resolution displayed in the preview from the camera.
The SelectedCamera property also provides the SupportedResolutions which makes it possible to determine which resolutions the current camera supports.
The following example shows how to add a Picker into the application and setup the following bindings:
- Bind the
ItemsSourceproperty of thePickerto theSupportedResolutionsof theSelectedCameraproperty. - Bind the
SelectedItemproperty of thePickerto theSelectedResolutionproperty on theCameraViewModelclass.
The final change involves binding the ImageCaptureResolution property of the CameraView to the SelectedResolution property on the CameraViewModel class.
<ContentPage
x:Class="CommunityToolkit.Maui.Sample.Pages.CameraViewPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">
<Grid ColumnDefinitions="*,*,*" RowDefinitions="*,30,30">
<toolkit:CameraView
Grid.ColumnSpan="3"
Grid.Row="0"
SelectedCamera="{Binding SelectedCamera}"
ZoomFactor="{Binding CurrentZoom}"
CameraFlashMode="{Binding FlashMode}"
ImageCaptureResolution="{Binding SelectedResolution}" />
<Slider
Grid.Column="0"
Grid.Row="1"
Value="{Binding CurrentZoom}"
Maximum="{Binding SelectedCamera.MaximumZoomFactor, FallbackValue=1}"
Minimum="{Binding SelectedCamera.MinimumZoomFactor, FallbackValue=1}"/>
<Picker
Grid.Column="1"
Grid.Row="1"
Title="Flash"
IsVisible="{Binding Path=SelectedCamera.IsFlashSupported, FallbackValue=false}"
ItemsSource="{Binding FlashModes}"
SelectedItem="{Binding FlashMode}" />
<Picker
Grid.Column="2"
Grid.Row="1"
Title="Available Resolutions"
ItemsSource="{Binding SelectedCamera.SupportedResolutions}"
SelectedItem="{Binding SelectedResolution}" />
</Grid>
</ContentPage>
CaptureImage
The CameraView provides the ability to programmatically trigger an image capture. This is possible through both the CaptureImage method or the CaptureImageCommand.
The following example shows how to add a Button into the application and setup the following bindings:
- Bind the
Commandproperty of theButtonto theCaptureImageCommandproperty on theCameraView.
<ContentPage
x:Class="CommunityToolkit.Maui.Sample.Pages.CameraViewPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">
<Grid ColumnDefinitions="*,*,*" RowDefinitions="*,30,30">
<toolkit:CameraView
x:Name="Camera"
Grid.ColumnSpan="3"
Grid.Row="0"
SelectedCamera="{Binding SelectedCamera}"
ZoomFactor="{Binding CurrentZoom}"
CameraFlashMode="{Binding FlashMode}" />
<Slider
Grid.Column="0"
Grid.Row="1"
Value="{Binding CurrentZoom}"
Maximum="{Binding SelectedCamera.MaximumZoomFactor, FallbackValue=1}"
Minimum="{Binding SelectedCamera.MinimumZoomFactor, FallbackValue=1}"/>
<Picker
Grid.Column="1"
Grid.Row="1"
Title="Flash"
IsVisible="{Binding Path=SelectedCamera.IsFlashSupported, FallbackValue=false}"
ItemsSource="{Binding FlashModes}"
SelectedItem="{Binding FlashMode}" />
<Picker
Grid.Column="2"
Grid.Row="1"
Title="Available Resolutions"
ItemsSource="{Binding SelectedCamera.SupportedResolutions}"
SelectedItem="{Binding SelectedResolution}" />
<Button
Grid.Column="0"
Grid.Row="2"
Command="{Binding CaptureImageCommand, Source={x:Reference Camera}}"
Text="Capture Image" />
</Grid>
</ContentPage>
Note
In order to use the image that has been captured the CameraView provides the MediaCaptured event.
Note
CaptureImage ends with the platform's answer to the capture. A failure that a command reports through the MediaCaptureFailed event while the capture waits, for example a video recording that StartVideoRecordingCommand can't start, doesn't end the capture.
The following example demonstrates how to use the CaptureImage method:
Note
The C# code below uses the Camera field defined above in XAML (<toolkit:CameraView x:Name="Camera" />)
async void HandleCaptureButtonTapped(object? sender, EventArgs e)
{
try
{
// Use the Camera field defined above in XAML (`<toolkit:CameraView x:Name="Camera" />`)
var captureImageCTS = new CancellationTokenSource(TimeSpan.FromSeconds(3));
Stream stream = await Camera.CaptureImage(captureImageCTS.Token);
}
catch(Exception ex)
{
// Handle Exception
Trace.WriteLine(ex);
}
}
Video Recording
The CameraView provides the ability to record videos. This is possible through both the StartVideoRecording method or the StartVideoRecordingCommand.
The following example shows how to add a Button into the application and setup the following bindings:
- Bind the
Commandproperty of theButtonto theStartVideoRecordingCommandproperty on theCameraView.
<ContentPage
x:Class="CommunityToolkit.Maui.Sample.Pages.CameraViewPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">
<Grid ColumnDefinitions="*,*,*" RowDefinitions="*,30,30">
<toolkit:CameraView
x:Name="Camera"
Grid.ColumnSpan="3"
Grid.Row="0"
SelectedCamera="{Binding SelectedCamera}"
ZoomFactor="{Binding CurrentZoom}"
CameraFlashMode="{Binding FlashMode}" />
<Slider
Grid.Column="0"
Grid.Row="1"
Value="{Binding CurrentZoom}"
Maximum="{Binding SelectedCamera.MaximumZoomFactor, FallbackValue=1}"
Minimum="{Binding SelectedCamera.MinimumZoomFactor, FallbackValue=1}"/>
<Picker
Grid.Column="1"
Grid.Row="1"
Title="Flash"
IsVisible="{Binding Path=SelectedCamera.IsFlashSupported, FallbackValue=false}"
ItemsSource="{Binding FlashModes}"
SelectedItem="{Binding FlashMode}" />
<Picker
Grid.Column="2"
Grid.Row="1"
Title="Available Resolutions"
ItemsSource="{Binding SelectedCamera.SupportedResolutions}"
SelectedItem="{Binding SelectedResolution}" />
<Button Clicked="StartCameraRecording"
Text="StartVideoRecording" />
<Button Command="{Binding StartVideoRecordingCommand, Source={x:Reference Camera}, x:DataType=toolkit:CameraView}"
CommandParameter="{Binding Stream}"
Text="StartVideoRecording" />
<Button Command="{Binding StopVideoRecordingCommand, Source={x:Reference Camera}, x:DataType=toolkit:CameraView}"
CommandParameter="{Binding Token}"
Text="StopVideoRecording" />
</Grid>
</ContentPage>
Note
You must provide a clean stream in order to record the video.
Note
StartVideoRecording throws a CameraException when the recording can't start, for example on iOS and Mac Catalyst when the camera permission isn't granted, or on Windows when the camera can't be opened. It throws an OperationCanceledException when its token is cancelled, or StopCameraPreview is called, before the recording started. See Cancel pending starts.
A recording starts and ends as follows:
- A second start joins the first. On Android, iOS, Mac Catalyst and Windows, a
StartVideoRecordingthat you call while an earlier one still waits for the platform to start the recording waits for that recording and returns when it has started. The stream of the second call receives no video. When the first start fails, the second call throws the same exception. - A start after a started recording replaces it. The video goes to the stream of the latest
StartVideoRecording, and the recording that ran before ends and its video is discarded. On Windows, the camera stays on between the two recordings, and the stream of the recording that ended goes back to the length and the position it had when that recording started, because Media Foundation writes into the stream while it records. On Android, an earlier version ignored the second start and kept the first recording. On Windows, an earlier version prepared a second recording without ending the first. - The camera is released while a start waits. On Android, iOS and Mac Catalyst, when the handler of the
CameraViewis disconnected, for example because the page closed, aStartVideoRecordingthat still waits throws aTaskCanceledException. - The preview was stopped. On Android, iOS, Mac Catalyst and Windows, a
StartVideoRecordingafter your app calledStopCameraPreview, or before it calledStartCameraPreview, starts the camera itself, and then the recording. The camera is off again once the recording ends (StopVideoRecordingreturns or throws; on Android, iOS and Mac Catalyst aStopVideoRecordingwhose token was cancelled before the video was copied leaves it on until the nextStopVideoRecording), unless your app started the preview: a preview that your app started keeps running, also when it callsStartCameraPreviewwhile the recording runs. When the camera can't start, a preview that was stopped stays stopped. On iOS, Mac Catalyst and Windows,StartVideoRecordingthen throws the failure, for example aCameraExceptionwithout a camera or when the camera can't be opened, and anUnauthorizedAccessExceptionon Windows when the privacy settings block the camera. On Android, aStartVideoRecordingwithout a camera returns without recording. - Stopping returns the video.
StopVideoRecordingreturns theStreamthat received the video. A furtherStopVideoRecordingafter the one that returned the video returnsStream.Null. On Android, iOS and Mac Catalyst it throws aCameraExceptionwhen the platform reports a recording that has no playable video. - A cancelled token doesn't keep the recording running. The token of
StopVideoRecordingonly cancels waiting for the video, not the stop. A token that is already cancelled, or that is cancelled while the stop waits for the video, still stops the recording that runs, andStopVideoRecordingthrows anOperationCanceledExceptioninstead of returning the video. CallStopVideoRecordingagain, with a token that isn't cancelled, to get the video. On Android, iOS and Mac Catalyst, a camera that the recording turned on stays on until then; on Windows it turns off with the cancelled stop. On Android, iOS and Mac Catalyst, a token that is cancelled while the video is being copied into your stream loses the video: the stream holds part of it, and the nextStopVideoRecordingreturnsStream.Null. A cancelled token while nothing records returnsStream.Null, unless a cancelled stop left a video for the nextStopVideoRecording: then it throws anOperationCanceledExceptionagain and keeps the video. A token that is cancelled while a start, or an earlier stop, still waits for the platform throws without stopping anything: a start that waits goes on and records.StopVideoRecordingCommandends without an event in every one of these cases. Everything else is the same on Android, iOS, Mac Catalyst and Windows. - Stopping the preview ends the recording.
StopCameraPreviewwhile a recording runs ends the recording. On Android, iOS and Mac Catalyst, a laterStopVideoRecordingreturns the video recorded until the stop, or throws aCameraExceptionwhen nothing playable was recorded. On Windows, it returnsStream.Null. - A failure to restore the camera after saving. On Android, the camera switches to a video session for the recording and back to the photo session afterwards. When that switch back fails after the video was written,
StopVideoRecordingstill returns the video, and the failure is reported through theErrorOccurredevent.
The following example demonstrates how to use the StartVideoRecording method:
Note
The C# code below uses the Camera field defined above in XAML (<toolkit:CameraView x:Name="Camera" />)
async void StartCameraRecordingWithCustomStream(object? sender, EventArgs e)
{
try
{
using var threeSecondVideoRecordingStream = new FileStream("recording.mp4", FileMode.Create);
await Camera.StartVideoRecording(threeSecondVideoRecordingStream, CancellationToken.None);
await Task.Delay(TimeSpan.FromSeconds(3));
await Camera.StopVideoRecording(CancellationToken.None);
await FileSaver.SaveAsync("recording.mp4", threeSecondVideoRecordingStream);
}
catch(OperationCanceledException)
{
// StopCameraPreview was called before the recording started
}
catch(Exception ex)
{
// Handle Exception
Trace.WriteLine(ex);
}
}
In case you want to record a short video and record video in MemoryStream you can use the next overload of VideoRecording:
async void StartCameraRecording(object? sender, EventArgs e)
{
try
{
await Camera.StartVideoRecording(CancellationToken.None);
await Task.Delay(TimeSpan.FromSeconds(3));
var threeSecondVideoRecordingStream = await Camera.StopVideoRecording(CancellationToken.None);
await FileSaver.SaveAsync("recording.mp4", threeSecondVideoRecordingStream);
}
catch(OperationCanceledException)
{
// StopCameraPreview was called before the recording started
}
catch(Exception ex)
{
// Handle Exception
Trace.WriteLine(ex);
}
}
Note
The task returned by StartVideoRecording completes successfully only after the platform confirms the recording has started, not when the start command is issued; await the returned task to be sure the recording is active before proceeding. On Android, a StartVideoRecording without a camera returns without recording, and a recording without the camera permission records no video: StopVideoRecording then throws a CameraException.
Start preview
The CameraView provides the ability to programmatically start the preview from the camera. This is possible through both the StartCameraPreview method or the StartCameraPreviewCommand.
The following example shows how to add a Button into the application and setup the following bindings:
- Bind the
Commandproperty of theButtonto theStartCameraPreviewCommandproperty on theCameraView.
<ContentPage
x:Class="CommunityToolkit.Maui.Sample.Pages.CameraViewPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">
<Grid ColumnDefinitions="*,*,*" RowDefinitions="*,30,30">
<toolkit:CameraView
x:Name="Camera"
Grid.ColumnSpan="3"
Grid.Row="0"
SelectedCamera="{Binding SelectedCamera}"
ZoomFactor="{Binding CurrentZoom}"
CameraFlashMode="{Binding FlashMode}" />
<Slider
Grid.Column="0"
Grid.Row="1"
Value="{Binding CurrentZoom}"
Maximum="{Binding SelectedCamera.MaximumZoomFactor, FallbackValue=1}"
Minimum="{Binding SelectedCamera.MinimumZoomFactor, FallbackValue=1}"/>
<Picker
Grid.Column="1"
Grid.Row="1"
Title="Flash"
IsVisible="{Binding Path=SelectedCamera.IsFlashSupported, FallbackValue=false}"
ItemsSource="{Binding FlashModes}"
SelectedItem="{Binding FlashMode}" />
<Picker
Grid.Column="2"
Grid.Row="1"
Title="Available Resolutions"
ItemsSource="{Binding SelectedCamera.SupportedResolutions}"
SelectedItem="{Binding SelectedResolution}" />
<Button
Grid.Column="0"
Grid.Row="2"
Command="{Binding CaptureImageCommand, Source={x:Reference Camera}}"
Text="Capture Image" />
<Button
Grid.Column="1"
Grid.Row="2"
Command="{Binding StartCameraPreviewCommand, Source={x:Reference Camera}}"
Text="Start Preview" />
</Grid>
</ContentPage>
The following example demonstrates how to use the StartCameraPreview method:
Note
The C# code below uses the Camera field defined above in XAML (<toolkit:CameraView x:Name="Camera" />)
async void HandleStartCameraPreviewButtonTapped(object? sender, EventArgs e)
{
try
{
var startCameraPreviewTCS = new CancellationTokenSource(TimeSpan.FromSeconds(3));
// Use the Camera field defined above in XAML (`<toolkit:CameraView x:Name="Camera" />`)
await Camera.StartCameraPreview(startCameraPreviewTCS.Token);
}
catch(OperationCanceledException)
{
// The token was cancelled, or StopCameraPreview was called, before the preview started
}
catch(Exception ex)
{
// Handle Exception
Trace.WriteLine(ex);
}
}
On Android, a StartCameraPreview that you call while the CameraView is still connecting to its camera waits for the connection, then starts the preview.
A preview that can't start doesn't throw an exception. StartCameraPreview and StartCameraPreviewCommand report it through the ErrorOccurred event on every platform. This includes a device without a camera, a camera permission that isn't granted, and a selected camera that can't be opened, for example because another app is using it. StartCameraPreview throws only an OperationCanceledException when the start is cancelled, an InvalidOperationException when the CameraView has no handler, for example before it is shown or after its handler was disconnected, and, on Android, the exception of a start that waited for a camera connection that failed and then failed as well (see below).
Camera.ErrorOccurred += (sender, e) => Trace.WriteLine(e.Exception);
Each failure raises ErrorOccurred once. On Android, when the camera connection that a StartCameraPreview waited for fails, ErrorOccurred reports that failure. If the StartCameraPreview then fails as well, for example because the camera permission isn't granted, it throws the exception to its caller instead of raising ErrorOccurred a second time. StartCameraPreviewCommand doesn't report that failure again.
On Windows, a StartCameraPreview while the preview runs does nothing. A StartCameraPreview while an earlier start is still opening the camera releases the camera of that earlier start, which ends without reporting an error.
What happens next depends on why the start failed:
- The selected camera can't be opened. The preview stays stopped, but it follows
SelectedCamera: selecting another camera starts the preview with that camera. This holds untilStopCameraPreviewis called. - The camera permission isn't granted. The preview stays stopped, and selecting another camera doesn't start it. Call
StartCameraPreviewagain once the app has the permission. On Android, the preview also starts by itself when the app resumes with the permission granted, for example after the user allowed it in the permission dialog or in the app's settings. This lets aCameraViewthat connects while your app asks for the permission start its preview without another call. A failure of that automatic start is reported throughErrorOccurred. Only the last start counts:StopCameraPreview, or a laterStartCameraPreview, cancels it.
Stop preview
The CameraView provides the ability to programmatically stop the preview from the camera. This is possible through both the StopCameraPreview method or the StopCameraPreviewCommand.
The following example shows how to add a Button into the application and setup the following bindings:
- Bind the
Commandproperty of theButtonto theStopCameraPreviewCommandproperty on theCameraView.
<ContentPage
x:Class="CommunityToolkit.Maui.Sample.Pages.CameraViewPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">
<Grid ColumnDefinitions="*,*,*" RowDefinitions="*,30,30">
<toolkit:CameraView
x:Name="Camera"
Grid.ColumnSpan="3"
Grid.Row="0"
SelectedCamera="{Binding SelectedCamera}"
ZoomFactor="{Binding CurrentZoom}"
CameraFlashMode="{Binding FlashMode}" />
<Slider
Grid.Column="0"
Grid.Row="1"
Value="{Binding CurrentZoom}"
Maximum="{Binding SelectedCamera.MaximumZoomFactor, FallbackValue=1}"
Minimum="{Binding SelectedCamera.MinimumZoomFactor, FallbackValue=1}"/>
<Picker
Grid.Column="1"
Grid.Row="1"
Title="Flash"
IsVisible="{Binding Path=SelectedCamera.IsFlashSupported, FallbackValue=false}"
ItemsSource="{Binding FlashModes}"
SelectedItem="{Binding FlashMode}" />
<Picker
Grid.Column="2"
Grid.Row="1"
Title="Available Resolutions"
ItemsSource="{Binding SelectedCamera.SupportedResolutions}"
SelectedItem="{Binding SelectedResolution}" />
<Button
Grid.Column="0"
Grid.Row="2"
Command="{Binding CaptureImageCommand, Source={x:Reference Camera}}"
Text="Capture Image" />
<Button
Grid.Column="1"
Grid.Row="2"
Command="{Binding StartCameraPreviewCommand, Source={x:Reference Camera}}"
Text="Start Preview" />
<Button
Grid.Column="2"
Grid.Row="2"
Command="{Binding StopCameraPreviewCommand, Source={x:Reference Camera}}"
Text="Stop Preview" />
</Grid>
</ContentPage>
The following example demonstrates how to use the StopCameraPreview method:
Note
The C# code below uses the Camera field defined above in XAML (<toolkit:CameraView x:Name="Camera" />)
void HandleStopCameraPreviewButtonTapped(object? sender, EventArgs e)
{
try
{
// Use the Camera field defined above in XAML (`<toolkit:CameraView x:Name="Camera" />`)
Camera.StopCameraPreview();
}
catch(Exception ex)
{
// Handle Exception
Trace.WriteLine(ex);
}
}
Cancel pending starts
StopCameraPreview also cancels what is still waiting for the platform to start:
- A
StartCameraPrevieworStartVideoRecording(both overloads) that hasn't completed. - The start that the
CameraViewmakes when it connects to its camera. - A camera switch, which is a change of
SelectedCamera. - On Android, the restart of the preview for a new
ImageCaptureResolution, and the automatic start that waits for the camera permission.
None of these is reported as a failure. The preview stays stopped until you call StartCameraPreview or StartVideoRecording again.
A caller that awaits a cancelled StartCameraPreview or StartVideoRecording gets an OperationCanceledException, as when its own token is cancelled. This happens, for example, when your app calls StopCameraPreview in OnDisappearing, or from a stop button, while the camera is still starting. The commands don't report it as an error. On iOS and Mac Catalyst, StartCameraPreview with a token that is already cancelled also throws an OperationCanceledException, and doesn't start the preview. On Windows, a StartCameraPreview that its own token cancels after the camera has opened stops the preview that it had shown, and releases the camera.
Important
Catch the OperationCanceledException when you await these methods, in particular in an async void handler, where an exception that escapes ends the app. Call the start again if you still need the preview or the recording after a StopCameraPreview interrupted its start.
Custom platform view
If your app sets CameraViewHandler.PlatformViewFactory, the CameraView shows the camera in the platform view that your factory returns:
- Android: the
PreviewViewkeeps what your app set on it, such as itsScaleType. - iOS and Mac Catalyst: the
CameraViewadds its preview to theUIView, behind the subviews of your app, and the preview follows the size of theUIView. - Windows: only a
MediaPlayerElementcan show the preview, and it keeps what your app set on it, such as itsStretch. With any other element, the camera works without a visible preview, and a warning is written to the trace output.
The view stays your app's. When the handler disconnects, the CameraView releases the camera, and on iOS and Mac Catalyst it removes its preview from the UIView, but it doesn't dispose your view.
Properties
| Property | Type | Description | Default Value |
|---|---|---|---|
CameraFlashMode |
CameraFlashMode |
Gets or sets the flash mode for the camera. This is a bindable property. | CameraFlashMode.Off |
ImageCaptureResolution |
Size |
Gets or sets the resolution for image capture. Does not affect the preview resolution. This is a bindable property. | Size.Zero |
IsAvailable |
bool |
Gets whether the camera is available on the device. This is a read-only bindable property. | false |
IsBusy |
bool |
Gets whether the camera is currently busy (e.g. capturing an image or recording). This is a read-only bindable property. | false |
IsTorchOn |
bool |
Gets or sets whether the camera torch (flashlight) is enabled. This is a bindable property. | false |
SelectedCamera |
CameraInfo? |
Gets or sets the currently selected camera device. This is a bindable property with two-way binding. | null |
ZoomFactor |
float |
Gets or sets the camera zoom factor. The value is automatically clamped to the selected camera's MinimumZoomFactor and MaximumZoomFactor. This is a bindable property. |
1f |
Commands
| Command | Command Parameter | Description |
|---|---|---|
CaptureImageCommand |
CancellationToken |
Triggers an image capture. The captured image is returned via the MediaCaptured event. A capture that fails is reported through the MediaCaptureFailed event. |
StartCameraPreviewCommand |
CancellationToken |
Starts the camera preview display. A preview that can't start is reported through the ErrorOccurred event. |
StartVideoRecordingCommand |
Stream |
Starts video recording into the Stream. A recording that can't start is reported through the MediaCaptureFailed event. |
StopCameraPreviewCommand |
— | Stops the camera preview display, and cancels a start that is still in progress. A failure is reported through the ErrorOccurred event. |
StopVideoRecordingCommand |
CancellationToken |
Stops video recording. The video is written to the Stream that was passed to StartVideoRecordingCommand. A failure is reported through the MediaCaptureFailed event. |
The commands let no exception escape. ICommand.Execute can't return the task of the work that a command starts, so an exception would reach no caller and end the app. Each failure is reported once, through the event in the table above. A command whose token is cancelled ends without an event, and so does a start that StopCameraPreview cancels.
Events
| Event | Type | Description |
|---|---|---|
MediaCaptured |
EventHandler<MediaCapturedEventArgs> |
Raised when an image is successfully captured. The MediaCapturedEventArgs contains a Media property of type Stream with the captured image data. |
MediaCaptureFailed |
EventHandler<MediaCaptureFailedEventArgs> |
Raised when an image capture fails, and when StartVideoRecordingCommand or StopVideoRecordingCommand fails. The MediaCaptureFailedEventArgs contains a FailureReason property with the error message. |
ErrorOccurred |
EventHandler<ErrorOccurredEventArgs> |
Raised when the camera reports an error that no caller can catch, or a failure that StartCameraPreview reports instead of throwing. This covers connecting the camera when the CameraView is shown, switching to the camera in SelectedCamera, applying ImageCaptureResolution, a preview that can't start, the automatic start on Android once the camera permission is granted and, on Windows, updating IsAvailable. The ErrorOccurredEventArgs contains an Exception property with the exception. A start that StopCameraPreview cancels isn't an error and isn't reported. Each failure is reported once. On Android, it is also raised when the camera can't switch back to the photo session at the end of StopVideoRecording, whether or not the video could be saved. |
Methods
| Method | Return Type | Description |
|---|---|---|
CaptureImage(CancellationToken) |
Task<Stream> |
Captures a single image from the camera and returns it. The image is also delivered via the MediaCaptured event. Throws a CameraException when the capture fails, for example when the preview hasn't started, and raises the MediaCaptureFailed event with the same reason. |
GetAvailableCameras(CancellationToken) |
ValueTask<IReadOnlyList<CameraInfo>> |
Retrieves a list of available camera devices on the device. |
StartCameraPreview(CancellationToken) |
Task |
Starts displaying the camera preview. A preview that can't start is reported through the ErrorOccurred event. Throws an OperationCanceledException when the token is cancelled, or StopCameraPreview is called, before the preview started. |
StartVideoRecording(CancellationToken) |
Task |
Starts recording video to an internal MemoryStream. Throws a CameraException when the recording can't start, and an OperationCanceledException when the token is cancelled, or StopCameraPreview is called, before the recording started. When it has to turn the camera on and can't, it throws the platform's failure instead, such as an UnauthorizedAccessException on Windows when the privacy settings block the camera; on Android, a start without a camera returns without recording. See Video Recording. |
StartVideoRecording(Stream, CancellationToken) |
Task |
Starts recording video to the provided Stream. Throws a CameraException when the recording can't start, and an OperationCanceledException when the token is cancelled, or StopCameraPreview is called, before the recording started. When it has to turn the camera on and can't, it throws the platform's failure instead, such as an UnauthorizedAccessException on Windows when the privacy settings block the camera; on Android, a start without a camera returns without recording. See Video Recording. |
StopCameraPreview() |
void |
Stops displaying the camera preview, and cancels a start of the preview or of a recording that is still in progress. |
StopVideoRecording(CancellationToken) |
Task<Stream> |
Stops video recording and returns the Stream that received the video, or Stream.Null when no recording runs. A cancelled token stops the recording that runs, then throws an OperationCanceledException; the next StopVideoRecording returns the video. Two exceptions: a token cancelled while a start, or an earlier stop, still waits stops nothing; and on Android, iOS and Mac Catalyst, a token cancelled while the video is copied into your stream leaves only part of it there, and the next StopVideoRecording returns Stream.Null. On Android, iOS and Mac Catalyst, throws a CameraException when the recording failed without a usable video. A recording that the platform ended early returns the video recorded until then. See Video Recording. |
CameraInfo
The CameraInfo class represents information about a camera device available on the system.
| Property | Type | Description |
|---|---|---|
DeviceId |
string |
The unique identifier of the camera device. |
IsFlashSupported |
bool |
Whether the camera supports flash. |
MaximumZoomFactor |
float |
The maximum supported zoom factor. |
MinimumZoomFactor |
float |
The minimum supported zoom factor. |
Name |
string |
The name of the camera device. |
Position |
CameraPosition |
The physical position of the camera on the device (Front, Rear, or Unknown). |
SupportedResolutions |
IReadOnlyList<Size> |
The list of resolutions supported by the camera for image capture. |
CameraFlashMode
The CameraFlashMode enum defines the available flash modes.
| Value | Description |
|---|---|
Off |
The flash is off and will not be used. |
On |
The flash is on and will always be used. |
Auto |
The flash will automatically be used based on the lighting conditions. |
CameraPosition
The CameraPosition enum defines the possible physical positions of a camera on a device.
| Value | Description |
|---|---|
Unknown |
The camera position is unknown. |
Front |
The camera is at the front of the device (facing the user). |
Rear |
The camera is at the rear of the device (facing away from the user). |
Examples
You can find an example of this feature in action in the .NET MAUI Community Toolkit Sample Application.
API
You can find the source code for CameraView over on the .NET MAUI Community Toolkit GitHub repository.
.NET MAUI Community Toolkit