【问题标题】:Image with stretch not displayed completely拉伸图像未完全显示
【发布时间】:2012-06-18 21:50:44
【问题描述】:

我想使用 Window 在网格行中显示一个(或可选的两个)图像。 此图像可能很大,因此我将 Stretch 属性设置为“UniformToFill”并将网格嵌入到滚动查看器中。

我的图像是应用程序。 800 x 400 像素,如果我尝试将其加载到我的窗口中,它不会以完整宽度显示(水平滚动条在图像结束之前停止)。

我希望图像填充可用的窗口区域,但能够滚动以完全查看。怎么了?

感谢您的帮助!

塔比娜

这是我的代码:

.xaml:

<Window x:Class="Wpf.Dialogs.ImageBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ImageBox" Topmost="True" WindowStartupLocation="CenterOwner"  Width="800" Height="600">
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" CanContentScroll="True">
  <Grid x:Name="gridImages">
    <Grid.RowDefinitions>
      <RowDefinition Height="*" />
      <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Image Grid.Row="0" x:Name="img1" Stretch="UniformToFill"/>
    <Image Grid.Row="1" x:Name="img2" Stretch="UniformToFill"/>
  </Grid>
</ScrollViewer>
</Window>

背后的代码:

using System;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;

namespace Wpf.Dialogs
{

public partial class ImageBox : Window
{
  public ImageBox() : this("Image", string.Empty, 800, 600)
  {
  }

  public ImageBox(string title, string image, int width, int height)
    : this(title, new string[] { image }, width, height)
  {
  }

  public ImageBox(string title, string[] images, int width, int height)
  {
    InitializeComponent();

    this.Title = title;
    this.Image = images;
  }


  public string[] Image
  {
    set
    {
      if (value != null)
      {
        var bim = CreateBitmap(value[0]);
        this.img1.Source = bim;

        if (value.Length == 2)
        {
          var bi = CreateBitmap(value[1]);

          if (bi != null)
          {
            this.img2.Source = bi;
          }
        }
        else
        {
          this.img2.Source = null;
        }
      }
    }
  }

  private BitmapImage CreateBitmap(string file)
  {
    if (File.Exists(file))
    {
      var bmp = new BitmapImage();
      bmp.BeginInit();
      bmp.UriSource = new Uri(file);
      bmp.CacheOption = BitmapCacheOption.OnLoad;
      bmp.EndInit();

      return bmp;
    }
    else
    {
      return null;
    }
  }
}

}

【问题讨论】:

    标签: wpf image scrollviewer stretch


    【解决方案1】:

    您不能同时使用 ScrollViewer 和 Stretch="UniformToFill"。使用 Grid 和 Stretch="UniformToFill" 或 ScrollViewer 和 Grid。

    【讨论】:

    • 那么我怎样才能让图像填充网格行(如缩放以适应),同时能够滚动查看图像的所有部分?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 2022-06-14
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多