WPF使用AForge實現Webcam預覽(二)

本文主要介紹如何讓攝像頭預覽界面的寬高比始終在16:9。html

首先咱們須要修改一下上一篇隨筆實現的UI界面,讓Grid變成一個3*3的九宮格,預覽界面位於正中間。Xaml示例代碼以下:express

<Window x:Class="WebcamPreview.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:controls="clr-namespace:AForge.Controls;assembly=AForge.Controls"
        mc:Ignorable="d"
        Title="Webcam" Height="360" Width="320" MinHeight="360" MinWidth="320" ResizeMode="CanResize" SizeChanged="Window_SizeChanged">
    <Grid  Background="Black">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="320" x:Name="col"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="360" x:Name="row"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="1" Grid.Column="1">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <WindowsFormsHost Background="Transparent">
                <controls:VideoSourcePlayer x:Name="VideoSourcePlayer1"/>
            </WindowsFormsHost>
            <WindowsFormsHost Background="Transparent" Grid.Row="1" >
                <controls:VideoSourcePlayer x:Name="VideoSourcePlayer2" />
            </WindowsFormsHost>
        </Grid>
    </Grid>
</Window>

指定Window的ResizeMode爲CanResize,這樣就咱們能夠調整窗口的大小了。ide

接下來就要實現windowSizeChanged事件。spa

private double radio = (double)16 / 9;

private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            int width = Convert.ToInt32(ActualWidth);
            int height = Convert.ToInt32(ActualHeight / 2);
            if (width > height * radio)
            {
                width = Convert.ToInt32(height * radio);
            }
            else
            {
                height = Convert.ToInt32(width / radio);
            }

            row.Height = new GridLength(height * 2);
            col.Width = new GridLength(width);
        }

 

這樣就能夠在咱們改變窗口大小的時候,使咱們視頻預覽的寬高比始終保持在16:9了。3d

最終效果以下:code

相關文章
相關標籤/搜索