WPF 使用Image控件显示图片

Image控件可以显示 .bmp, .gif, .ico, .jpg, .png, .wdp and .tiff 格式的图片文件。

1. 使用Source属性显示图片

UI 添加Image控件

<Image x:Name="ImageViewer1" Height="100" Width="200"/>

后台代码给Source属性赋值

ImageViewer1.Source = new BitmapImage(new Uri(@"Images\\VS2015.jpg", UriKind.Relative));

效果图如下:

WPF 使用Image控件显示图片_第1张图片

动态切换Source 指定的文件,使用OpenFileDialog 类来选择图片源文件

首先需要添加System.Windows.Forms的引用,来选择磁盘上其它图片文件来展示

private void btnUrl_Click(object sender, RoutedEventArgs e)
        {

            OpenFileDialog dlg = new OpenFileDialog();

            dlg.InitialDirectory = "c:\\";

            dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";

            dlg.RestoreDirectory = true;

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)

            {

                string selectedFileName = dlg.FileName;

                txtFile.Text = selectedFileName;

                BitmapImage bitmap = new BitmapImage();

                bitmap.BeginInit();

                bitmap.UriSource = new Uri(selectedFileName);

                bitmap.EndInit();

                ImageViewer1.Source = bitmap;

            }

        }

上述方法需要运行代码才能展示图片的。

2. 直接在WPF设计UI上展示图片

直接在XAML代码中

效果如下:

WPF 使用Image控件显示图片_第2张图片

直接展示在界面上,无须运行代码。

可以设置图片显示的宽度和高度。

<Image x:Name="ImageViewer3" Source="Images\\USA.png" Width="100" Height="100"/>

效果如下:

WPF 使用Image控件显示图片_第3张图片

使用BitmapImage方式

<Image Width="100">
    <Image.Source>
      <BitmapImage DecodePixelWidth="100"  UriSource="Images\\USA.png" />
    </Image.Source>
</Image>

3.动态添加Image控件,并显示图片

<StackPanel x:Name="sp1" Grid.Row="0" Grid.Column="2" Margin="5">
   <Button x:Name="btnDynamic" Click="btnDynamic\_Click">动态加载</Button>
 </StackPanel>

后台代码:

private void btnDynamic_Click(object sender, RoutedEventArgs e)
{

    // Create Image and set its width and height 
    Image dynamicImage = new Image();
    dynamicImage.Width = 300;
    dynamicImage.Height = 200;
    
    // Create a BitmapSource 
    BitmapImage bitmap = new BitmapImage();
    bitmap.BeginInit();
    bitmap.UriSource = new Uri(@"C:\\Users\\WPF加载图片文件\\WpfApp1\\Images\\VS2015.png");
    bitmap.EndInit();

    // Set Image.Source 
    dynamicImage.Source = bitmap;
    // Add Image to Window 
    sp1.Children.Add(dynamicImage);
}

效果如下:

WPF 使用Image控件显示图片_第4张图片

你可能感兴趣的:(C#,编程,wpf,c#,Image,展示图片文件)