我目前正在开发一个UWP应用程序,我的程序中有一个摄像头功能。但是,我希望为该功能实现计时器。
我希望允许用户在侧面选择他们的首选时间,然后点击"拍照"按钮和在相机屏幕上它将显示一个计时器和onclick下的事件为"拍照"按钮将根据用户的选择而延迟。
这是我的代码来自.xaml:
<CaptureElement Name="PreviewControl" Margin="566,77,166,50"/>
<Button x:Name="PhotoButton" Content="Take a picture!" HorizontalAlignment="Left" Margin="990,678,0,-91" VerticalAlignment="Top" Click="PhotoButton_Click" Height="45" Width="313" Background="White" Foreground="Black"/>
//Timer buttons
<Button x:Name="Timer_3sec" Content="3 seconds" HorizontalAlignment="Left" Margin="138,125,0,0" VerticalAlignment="Top" Height="66" Width="262" Background="White" Foreground="Black"/>
<Button x:Name="Timer_5sec" Content="5 seconds" HorizontalAlignment="Left" Margin="138,234,0,0" VerticalAlignment="Top" Height="66" Width="262" Background="White" Foreground="Black"/>
<Button x:Name="Timer_7sec" Content="7 seconds" HorizontalAlignment="Left" Margin="138,337,0,0" VerticalAlignment="Top" Height="66" Width="262" Background="White" Foreground="Black"/>
来自xaml.cs的代码:
private async void PhotoButton_Click(object sender, RoutedEventArgs e)
{
await TakePhotoAsync();
}
private async Task TakePhotoAsync()
{
var stream = new InMemoryRandomAccessStream();
Debug.WriteLine("Taking photo...");
await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
try
{
var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName);
Debug.WriteLine("Photo taken! Saving to " + file.Path);
var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());
await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
Debug.WriteLine("Photo saved!");
await Helpers.MessageDialogHelpers.ShowNoActionMessageBox("Your photo has been taken!", "");
}
catch (Exception ex)
{
// File I/O errors are reported as exceptions
Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
}
}
答案 0 :(得分:2)
在代码后面创建一个字段:
private int _seconds;
在按钮处理程序中设置适当的时间:
private void Timer_3sec_Click(object sender, RoutedEventArgs e)
{
_seconds = 3;
}
将延迟添加到照片按钮处理程序:
private async void PhotoButton_Click(object sender, RoutedEventArgs e)
{
await Task.Delay(TimeSpan.FromSeconds(_seconds));
await TakePhotoAsync();
}
这应该足够了。如果您发现后面的代码变得复杂,因为您要添加所有逻辑,那么请尝试阅读有关MVVM的内容。