0

我正在尝试在我的应用程序中更改我的相机的 CameraType (FrontFacing/Primary)。

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>

    <Canvas x:Name="viewfinderCanvas" Width="720" Height="480" 
               HorizontalAlignment="Left" >

        <!--Camera viewfinder -->
        <Canvas.Background>
            <VideoBrush x:Name="viewfinderBrush" />
        </Canvas.Background>

        <!-- Brackets for Touch Focus -->
        <TextBlock 
            x:Name="focusBrackets" 
            Text="[   ]" 
            FontSize="40"
            Visibility="Collapsed"/>

    </Canvas>

    <!--Button StackPanel to the right of viewfinder>-->
    <StackPanel Grid.Column="1" >
        <Button Content="Front" Name="btCameraType" Click="changeFacing_Clicked" FontSize="26" FontWeight="ExtraBold" Height="75"/>
    </StackPanel>

    <!--Used for debugging >-->
    <TextBlock Height="40" HorizontalAlignment="Left" Margin="8,428,0,0" Name="txtDebug" VerticalAlignment="Top" Width="626" FontSize="24" FontWeight="ExtraBold" />
</Grid>

这是背后的代码:

private void changeFacing_Clicked(object sender, RoutedEventArgs e)
{
    if (cam.CameraType == CameraType.FrontFacing)
        cam = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
    else
        cam = new Microsoft.Devices.PhotoCamera(CameraType.FrontFacing);
    viewfinderBrush.Dispatcher.BeginInvoke(delegate()
    {
        viewfinderBrush.SetSource(cam);
    });
}

所以我实际上只是在用户单击按钮时更改 CameraType。问题是当用户点击按钮几次(比如在 2 秒内点击 5 次)时,程序无法处理它并且停止工作......关于如何避免这个问题的任何解决方案?

我也尝试过启用/禁用按钮,但我仍然可以单击按钮..

4

1 回答 1

2

问题是当用户点击按钮几次(比如 2 秒内 5 次)时,程序无法处理它并停止工作

以我的经验,我注意到这个PhotoCamera类有抛出很多异常的趋势,有时是因为一些模糊的原因。

我可能会得到一些反对意见,但我会这样做:将代码放在一个try...catch块中,如下所示:

try
{
    if (cam.CameraType == CameraType.FrontFacing)
        cam = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
    else
        cam = new Microsoft.Devices.PhotoCamera(CameraType.FrontFacing);
    viewfinderBrush.Dispatcher.BeginInvoke(delegate()
    {
        viewfinderBrush.SetSource(cam);
    });
}
catch (Exception) { }

当然,在使用 FrontFacing 摄像头之前,您需要检查设备是否有:

PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing)

编辑
根据评论,该try..catch方法还不够。这是一个更丑陋的解决方案,应该可以工作:

DateTime lastChange = DateTime.MinValue;
private void changeFacing_Clicked(object sender, RoutedEventArgs e)
{
    TimeSpan elapsedTime = DateTime.Now - lastChange;
    if (elapsedTime.TotalMilliseconds < 2000) // If the last change occured less than 2 seconds ago, ignore it
        return;

    if (cam.CameraType == CameraType.FrontFacing)
        cam = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
    else
        cam = new Microsoft.Devices.PhotoCamera(CameraType.FrontFacing);

    viewfinderBrush.Dispatcher.BeginInvoke(delegate()
    {
        viewfinderBrush.SetSource(cam);
    });

    lastChange = DateTime.Now;
}
于 2013-07-02T08:27:04.390 回答