Metro style .net app Image控件的使用

Image 元素:
Object
      |------DependencyObject
             | -----UIElement

|--------FrameworkElement

|---------Image

常见用法:<Image Source="Assets/Logo.png" />
其中image.Source是一个ImageSource类型:
Object
       |----- DependencyObject

   |----- ImageSource

|------BitmapSource

|-----BitmapImage

|-----WriteableBitmap

 

ImageSource包含(封装)了实际要显示的图片,但是它本身是个抽象类,不能被实例化,需要它的继承类来初始化。其中BitmapSource也是抽象类(抽象位图,以像素为单位来描述自身的宽和高,这样的信息都被编码在了位图文件中),不能初始化,但是它的PixelWidth和PixelHeight属性说明图片在加载成功后的大小.而它的SetSource(IRandomAccessStream streamSource)方法可以让你从文件或网络流中读取Bitmap数据。
BitmapImage继承了BitmapSource,并且还添加了支持URI的UriSource属性。它的构造函数也支持传递URI对象来实例化自己。
示例代码:

 

Uri uri = new Uri("http://www.charlespetzold.com/pw6/PetzoldJersey.jpg"); 
BitmapImage bitmap = new BitmapImage(uri); 
Image image = new Image();
 image.Source = bitmap; 
contentGrid.Children.Add(image);

 

 

 使用Http下载图片流进行初始化:

 

HttpClient httpClient = new HttpClient( new HttpClientHandler());
 async Task<IRandomAccessStream> getImageStream(string url)
 {
   Stream stream=await httpClient.GetStreamAsync(url);
 var randomAccessStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
 awaitRandomAccessStream.CopyAsync(stream.AsInputStream(),randomAccessStream.GetOutputStreamAt(0));
 stream.Dispose();
     return randomAccessStream;
       }
async void foo(Uri IconUri){

Image img = new Image();
                  BitmapImage bitmapImage = new BitmapImage();
                  bitmapImage.SetSource(await getImageStream(IconUri));
                  img.Source=bitmapImage;
                     img.MaxWidth = 60;
                    img.MaxHeight = 60;
                    img.Stretch = Windows.UI.Xaml.Media.Stretch.UniformToFill;
                 bitmapImage.ImageOpened+=(o,e)=>{//确保BitmapImage的宽高已经有值
                    int w = bitmapImage.PixelWidth > 60 ? 60 : bitmapImage.PixelWidth;
                    int h = bitmapImage.PixelHeight > 60 ? 60 : bitmapImage.PixelHeight;
                  }            
}

  

 

 Stretch属性的四个值:

None 显示图片保持原始大小
Fill 重新对图片设置大小来填充目标大小
Uniform 按原图宽高比例就行缩放填充适应目标
UniformToFill 按原图宽高比例进行缩放填充,但是可能因为不适合目标比例而被部分截断

 



DecodePixelHeight和Width属性:
若设置了BitmapImage的这两个值,那么将会加载指定大小的图片,即放弃原有图片的大小和高宽比例。否则加载的图片的高宽比将不变,然后根据Stretch进行缩放。
JPEG和PNG解码器解析图片到指定的大小。而其他的解码器则加载图片的原始大小,然后缩放到目标大小。
示例代码:

 

 

using (IRandomAccessStream fileStream = await        file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    // Set the image source to the ed bitmap
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.DecodePixelHeight = decodePixelHeight;
                    bitmapImage.DecodePixelWidth = decodePixelWidth;
                    bitmapImage.SetSource(fileStream);
                  FooImage.Source = bitmapImage;                
                }

 

 

 参考资料:the 6th edition of Programming Windows,Charles Petzold

你可能感兴趣的:(image)