Windows Phone 8.1应用程序全屏显示图像预览

本文关键字:显示图 显示 图像 Phone 应用程序 Windows | 更新日期: 2023-09-27 18:29:36

在我的Windows Phone 8.1应用程序上,我有摄像头功能,但我似乎无法全屏显示图像预览。有人能看到必须做什么吗?

ButtonCapture_Click初始化imagePreview,previewElement_Tapped实际拍摄快照。

Xaml

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="0,18,0,18">
        <TextBlock Text="StudyToolMobile" Style="{StaticResource TitleTextBlockStyle}" Margin="18,0"/>
    </StackPanel>
    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="18,0,18,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="4*" />
            <ColumnDefinition Width="2*" />
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="0" Grid.ColumnSpan="2" Style="{StaticResource BodyTextBlockStyle}" Text="Enter some text below and click Save to insert a new TodoItem item into your database" TextWrapping="Wrap"/>
        <TextBox Grid.Row="1" Grid.Column="0" Name="TextInput" Text="" />
        <StackPanel Grid.Row ="1" Grid.Column="1"  Orientation="Horizontal">
            <AppBarButton Label="Photo" Icon="Camera" Name="ButtonCapture" 
              Click="ButtonCapture_Click" Height="78" Width="62" />
            <AppBarButton Label="Upload" Icon="Upload" Name="ButtonSave" 
              Click="ButtonSave_Click"/>
        </StackPanel>
        <Grid Grid.Row="2" Name="captureGrid" Grid.RowSpan="3" Grid.ColumnSpan="2" 
  Canvas.ZIndex="99" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" 
  Visibility="Collapsed">
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <CaptureElement Grid.Row="0" x:Name="previewElement" Tapped="previewElement_Tapped" />
            <Image Grid.Row="0" Name="imagePreview" Visibility="Collapsed" Margin="0,262,0,115"  />
            <StackPanel Grid.Row="1" Name="captureButtons" 
            Orientation="Horizontal" Visibility="Collapsed">
                <TextBlock Name="TextCapture" VerticalAlignment="Bottom" />
                <AppBarButton Label="Retake" Icon="Redo" Name="ButtonRetake" 
                  Click="ButtonRetake_Click" />
                <AppBarButton Label="Cancel" Icon="Cancel" Name="ButtonCancel" 
                  Click="ButtonCancel_Click" />
            </StackPanel>
        </Grid>
        <TextBlock Grid.Row="2" Grid.ColumnSpan="2" Style="{StaticResource BodyTextBlockStyle}" Text="Click refresh below to load the unfinished TodoItems from your database. Use the checkbox to complete and update your TodoItems" TextWrapping="Wrap"/>
        <Button Grid.Row="3" Grid.ColumnSpan="2" Name="ButtonRefresh" Click="ButtonRefresh_Click" HorizontalAlignment="Stretch">Refresh</Button>
        <ListView  Grid.Row="4" Grid.ColumnSpan="2" Name="ListItems">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <CheckBox Name="CheckBoxComplete" IsChecked="{Binding Complete, Mode=TwoWay}" 
                            Checked="CheckBoxComplete_Checked" Content="{Binding Text}" 
                            Margin="10,5" VerticalAlignment="Center"/>
                        <Image Name="ImageUpload" Source="{Binding ImageUri, Mode=OneWay}" 
                            MaxHeight="150"/>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Grid>

代码

    // Use a StorageFile to hold the captured image for upload.
    StorageFile media = null;
    MediaCapture cameraCapture;
    bool IsCaptureInProgress;
    private async Task CaptureImage()
    {
        // Capture a new photo or video from the device.
        cameraCapture = new MediaCapture();
        cameraCapture.Failed += cameraCapture_Failed;
        // Initialize the camera for capture.
        await cameraCapture.InitializeAsync();
        cameraCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
        cameraCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);

        captureGrid.Visibility = Windows.UI.Xaml.Visibility.Visible;
        previewElement.Visibility = Windows.UI.Xaml.Visibility.Visible;
        previewElement.Source = cameraCapture;
        await cameraCapture.StartPreviewAsync();
    }
    private async void previewElement_Tapped(object sender, TappedRoutedEventArgs e)
    {
        // Block multiple taps.
        if (!IsCaptureInProgress)
        {
            IsCaptureInProgress = true;
            Random rnd = new Random();
            int number = rnd.Next(1, 20);
            string numberString = number.ToString();
            string jpgName = numberString + ".jpg";

            // Create the temporary storage file.
            media = await ApplicationData.Current.LocalFolder
                .CreateFileAsync(jpgName, CreationCollisionOption.ReplaceExisting);
            // Take the picture and store it locally as a JPEG.
            await cameraCapture.CapturePhotoToStorageFileAsync(
                ImageEncodingProperties.CreateJpeg(), media);
            captureButtons.Visibility = Visibility.Visible;
            // Use the stored image as the preview source.
            BitmapImage tempBitmap = new BitmapImage(new Uri(media.Path));
            imagePreview.Source = tempBitmap;
            imagePreview.Visibility = Visibility.Visible;
            previewElement.Visibility = Visibility.Collapsed;
            IsCaptureInProgress = false;
        }
    }
    private async void cameraCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs)
    {
        // It's safest to return this back onto the UI thread to show the message dialog.
        MessageDialog dialog = new MessageDialog(errorEventArgs.Message);
        await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
            async () => { await dialog.ShowAsync(); });
    }
    private async void ButtonCapture_Click(object sender, RoutedEventArgs e)
    {
        // Prevent multiple initializations.
        ButtonCapture.IsEnabled = false;
        await CaptureImage();
    }

Windows Phone 8.1应用程序全屏显示图像预览

您已将"边距"设置为图像预览。将上下边距设置为0,这样图像将占用全部空间。。。

  <Image Grid.Row="0" Name="imagePreview" Visibility="Collapsed" Margin="0"  />

不要使用以下API:

cameraCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
cameraCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);

相反,要旋转预览和录制的视频,请参阅CameraStarterKit SDK示例:

    /// <summary>
    /// Gets the current orientation of the UI in relation to the device (when AutoRotationPreferences cannot be honored) and applies a corrective rotation to the preview
    /// </summary>
    private async Task SetPreviewRotationAsync()
    {
        // Only need to update the orientation if the camera is mounted on the device
        if (_externalCamera) return;
        // Calculate which way and how far to rotate the preview
        int rotationDegrees = ConvertDisplayOrientationToDegrees(_displayOrientation);
        // The rotation direction needs to be inverted if the preview is being mirrored
        if (_mirroringPreview)
        {
            rotationDegrees = (360 - rotationDegrees) % 360;
        }
        // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames
        var props = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
        props.Properties.Add(RotationKey, rotationDegrees);
        await _mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, null);
    }

和:

    /// <summary>
    /// Records an MP4 video to a StorageFile and adds rotation metadata to it
    /// </summary>
    /// <returns></returns>
    private async Task StartRecordingAsync()
    {
        try
        {
            // Create storage file in Pictures Library
            var videoFile = await KnownFolders.PicturesLibrary.CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption.GenerateUniqueName);
            var encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
            // Calculate rotation angle, taking mirroring into account if necessary
            var rotationAngle = 360 - ConvertDeviceOrientationToDegrees(GetCameraOrientation());
            encodingProfile.Video.Properties.Add(RotationKey, PropertyValue.CreateInt32(rotationAngle));
            Debug.WriteLine("Starting recording...");
            await _mediaCapture.StartRecordToStorageFileAsync(encodingProfile, videoFile);
            _isRecording = true;
            Debug.WriteLine("Started recording!");
        }
        catch (Exception ex)
        {
            // File I/O errors are reported as exceptions
            Debug.WriteLine("Exception when starting video recording: {0}", ex.ToString());
        }
    }