一、显示图片的相关类
1、Image
类
- WPF中主要通过
Image
类来进行显示图片。可以通过XAML
标记语言或者C#
来进行设置。 - 设置图片的尺寸时,一般只设置
Image
类的Width或Height中的一个,若同时设置这两个属性,则图片可能会发生变形扭曲。 - 在加载图像内容之前,控件的ActualWidth和ActualHeight 为零,因为图像内容用于确定控件的最终大小和位置
2、BitmapImage
类
BitmapImage
主要用于支持XAML语言,并为位图加载时添加BitmapSource
未定义的其他属性。- 为加载图片时提供优化,从而让应用程序在加载图片时,能够更好的使用内存。
BitmapImage
的属性设置必须要在 BeginInit和 EndInit之间进行。
3、BitmapSource
类
二、应用实例
1、直接通过Image
来显示图片
- 通过该方式来显示图片,将导致应用程序不能更好的优化利用内存。
- 一般不使用该方式来显示图片
<Image Source="D:\WSpace\ImgFile\Natural\11.jpeg"/>
2、从外部文件中直接加载图片的方式
- 通过
BitmapImage
位图来对优化图片的加载方式,为常用的方式
// C#形式
/*********** 方法1: ************/
Uri uri01 = new Uri(@"D:\WSpace\ImgFile\Natural\12.jpeg");
BitmapImage bitmapImage01 = new BitmapImage(uri01);
Image image01 = new Image();
image01.Source = bitmapImage01; //将图片的Source设置为位图
/*********** 方法2: ************/
// 创建图片的Source
BitmapImage bitmapImage02 = new BitmapImage();
bitmapImage02.BeginInit();
bitmapImage02.UriSource = new Uri(@"D:\WSpace\ImgFile\Natural\12.jpeg"); // BitmapImage.UriSource 必须在 BeginInit/EndInit 之间
bitmapImage02.EndInit();
//创建Image对象,并将其Source设定为位图
Image image02 = new Image();
image02.Source = bitmapImage02;
<!--XAML形式-->
<Image Grid.Row="1" Grid.Column="0">
<Image.Source>
<BitmapImage UriSource="D:\WSpace\ImgFile\Design\01.jpeg"/>
</Image.Source>
</Image>
3、将图片加入到项目资源中,成为组件资源
- 图片作为组件资源会和项目一起进行编译,成为
exe
文件或dll
文件。 - 一般先在当前方案下创建
Images
目录来存放需要的图片,再将图片添加到该目录下,如下图右键Images
选中添加Existing Item....
,选择需要添加的图片即可。同时确保图片Properties
的Build Action
对应值为Resource
。 - 使用时需要格外注意路径的设置,其路径格式如下:
-
pack://application:,,,/ReferencedAssembly;component/引用程序集下图片的相对路径
。
①路径中:ReferencedAssembly
为图片资源所在的程序集,一般为当前项目名称。
②component/
后面为引用程序集下图片资源的相对路径。
-
- 以代码的形式加载资源中图片应用实例如下,此时在代码中不可以使用相对路径的形式:
- 在
XAML
中加载资源中的图片的方式(文件结构同上图)
<!--通过将图片设置为字典key-value的形式,供第3种方式使用-->
<Window.Resources>
<BitmapImage x:Key="imgKey" UriSource="./Images/06.jpeg"/> <!--UriSource可以使用相对路径-->
</Window.Resources>
<!--1. 使用相对路径的形式-->
<Image Grid.Row="1" Grid.Column="1">
<Image.Source>
<BitmapImage UriSource="./Images/02.jpeg"/>
</Image.Source>
</Image>
<!--2. 使用pack://application:,,,的形式-->
<Image Grid.Row="1" Grid.Column="2">
<Image.Source>
<BitmapImage UriSource="pack://application:,,,/Pr60_TestFunction;component/F02_ShowImage/Images/05.jpeg"/>
</Image.Source>
</Image>
<!--3. 使用资源的Key-Value的形式-->
<Image Grid.Row="2" Grid.Column="2" Source="{StaticResource imgKey}"/>