日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

WPF 使用Image控件显示图片

發布時間:2023/12/20 asp.net 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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));

效果圖如下:

動態切換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代碼中

效果如下:

直接展示在界面上,無須運行代碼。

可以設置圖片顯示的寬度和高度。

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

效果如下:

使用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控件显示图片的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。