本文主要介绍如何让摄像头预览界面的宽高比始终在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
接下来就要实现window的SizeChanged事件。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