Image控件可以显示 .bmp, .gif, .ico, .jpg, .png, .wdp and .tiff 格式的图片文件。
1. 使用Source属性显示图片
UI 添加Image控件
后台代码给Source属性赋值
ImageViewer1.Source = new BitmapImage(new Uri(@"Images\VS2015.jpg", UriKind.Relative));
效果图如下:
动态切换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代码中
效果如下:
直接展示在界面上,无须运行代码。
可以设置图片显示的宽度和高度。
效果如下:
使用BitmapImage方式
3.动态添加Image控件,并显示图片
后台代码:
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);
}
效果如下: