//xaml文件(界面)
<Grid Background="Black" x:Name="GridGroup">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60"/>
<ColumnDefinition/>
<ColumnDefinition Width="60"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1" x:Name="GridImages">
<Grid.RowDefinitions>
<RowDefinition Height="0"/>
<RowDefinition/>
<RowDefinition Height="0"/>
</Grid.RowDefinitions>
<Grid Grid.Row="1" Background="Black"
x:Name="touchPad"
PreviewMouseDown="Grid_PreviewMouseDown"
PreviewMouseUp="Grid_PreviewMouseUp"
PreviewMouseMove ="Grid_PreviewMouseMove">
<Image x:Name="image_show" Stretch="Fill"
Source="pack://application:,,,/Resources/LedOpen.png">
<Image.RenderTransform>
<MatrixTransform></MatrixTransform>
</Image.RenderTransform>
</Image>
<Canvas x:Name="CanvasImage" Background="Transparent" Focusable="True"
Width="{Binding ActualWidth, Mode=Default, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}"
Height="{Binding ActualHeight, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}">
<Rectangle x:Name="rectangle" Stroke="Red" Fill="Transparent" StrokeThickness="2"
Width="0" Height="0" Canvas.Left="100" Canvas.Top="100"
/>
</Canvas>
</Grid>
</Grid>
</Grid>
//cs文件(后台)
//界面Load时,控件已经布置完毕,可开始获取控件尺寸,并重新设置尺寸
private void Window_Loaded(object sender, RoutedEventArgs e)
{
InvalidaView();
}
/// <summary>
/// 根据图片尺寸重新刷新图片显示
/// </summary>
private void InvalidaView()
{
//图片控件source的尺寸
double imageHeight = image_show.Source.Height;
double imageWidth = image_show.Source.Width;
//外围Grid的实际尺寸
double dAHeight = GridGroup.ActualHeight;
double dAWidth = GridGroup.ActualWidth;
//声明最终图片需要设置成的尺寸
double needWidth = 0;
double needHeight = 0;
//图片尺寸最终要变成控件的尺寸
//控件尺寸最为分母,哪个的尺寸小就是哪个为主
if (dAHeight / imageHeight < dAWidth / imageWidth )
{
needHeight = dAHeight;
needWidth = imageWidth * (dAHeight / imageHeight);
}
else
{
needHeight = imageHeight * (dAWidth / imageWidth);
needWidth = dAWidth;
}
//设置外围Grid尺寸的宽度
double dOffset = (dAWidth - needWidth) / 2;
ColumnDefinitionCollection cdc = GridGroup.ColumnDefinitions;
cdc[0].Width = new GridLength(dOffset);
cdc[1].Width = new GridLength(needWidth);
cdc[2].Width = new GridLength(dOffset);
//设置图片控件所在Grid的高度
RowDefinitionCollection rdc = GridImages.RowDefinitions;
double dOffsetImage = (dAHeight - needHeight) / 2;
rdc[0].Height = new GridLength(dOffsetImage);
rdc[1].Height = new GridLength(needHeight);
rdc[2].Height = new GridLength(dOffsetImage);
//强制刷新界面
InvalidateVisual();
}