在WP7中使用Stretch = UniformToFill的图像控件

4
我在页面上放置了一个图片,如下所示:
<Grid x:Name="LayoutRoot" Background="Transparent">
   <Grid.RowDefinitions>
     <RowDefinition Height="Auto"/>
     <RowDefinition Height="*"/>
   </Grid.RowDefinitions>

<Image Name="im" Source="/images/hqdefault.jpg" Height="250" Stretch="UniformToFill"  VerticalAlignment="Center"/>
    </Grid>

这是整个页面的XAML代码,图片可以从http://i.ytimg.com/vi/wNKKCHv-oOw/hqdefault.jpg下载。

代码后台包含一些逻辑来处理页面方向改变事件。

 private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
 {
    if (Orientation == PageOrientation.Landscape ||
        Orientation == PageOrientation.LandscapeLeft ||
        Orientation == PageOrientation.LandscapeRight)
    {
       im.Height = Application.Current.Host.Content.ActualWidth;
       im.Width = Application.Current.Host.Content.ActualHeight;

       im.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
       im.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
     }
     else
     {
       im.Height = 250;
       im.Width = Application.Current.Host.Content.ActualWidth;
     }
  }

如果有人尝试这个功能,他/她可能会发现StrechToFill会从底部裁剪图像内容,而我希望它能够从顶部和底部均匀裁剪,并在图像控件内使图像内容居中。
希望我表达清楚了,如果没有,请考虑使用提供的代码制作示例。非常感谢。
2个回答

8
主要问题是在Image控件上设置高度或宽度,我现在很清楚不要在图像控件或媒体元素上设置高度或宽度。如果您需要固定高度,例如在纵向模式下,可以将其放在网格控件中并设置其高度或宽度。以下是适用于我的代码。
<Grid Name="grdMedia"
      Grid.Row="1" 
      VerticalAlignment="Stretch" 
      HorizontalAlignment="Stretch"
      Height="250">
<Image Name="imThumbnail" 
       Grid.Row="1" 
       Stretch="UniformToFill" 
       HorizontalAlignment="Center"
       VerticalAlignment="Center"/>
</Grid>

如果您想在横屏模式下将此图片变成全屏,请使用以下代码:

    private void SetUIInLandscape()
    {
        SystemTray.IsVisible = false;

       //Do not change the height or width of image control nor its alignments 
       //Hide every thing else

        grdMedia.Height = Application.Current.Host.Content.ActualWidth;
        grdMedia.Width = Application.Current.Host.Content.ActualHeight;

    }

    private void SetUIInPortrait()
    {
        SystemTray.IsVisible = true;

        //Do not change the height or width of image control nor its alignments
        //Make every thing else visible

        grdMedia.Height = 250;
        grdMedia.Width = Application.Current.Host.Content.ActualWidth;
    }

3
<Grid x:Name="LayoutRoot" Background="Transparent">
   <Grid.RowDefinitions>
     <RowDefinition Height="Auto"/>
     <RowDefinition Height="*"/>
  </Grid.RowDefinitions>

<Image Name="im" Source="/images/hqdefault.jpg" Height="Auto" HorizontalAlignment="Stretch"  VerticalAlignment="Center"/>
</Grid>

尝试这样做,那么您就不需要在PhoneApplicationPage_OrientationChanged事件中做任何事情。


这是一个问题,当我将Stretch设置为UniformToFill时,它会使其底部对齐而不是居中。 - Mubashar
我认为如果你只是把它删除,一切都会好起来... 尝试删除它,只留下我提到的内容。 - Apoorva
如果图像的大小大于行高,则图像将采用行高。否则,如果使用Height,则它将采用其原始高度。 - Apoorva

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接