Fork me on GitHub

UWP-本地图片选取

Week 2

上次完成了标题栏的透明化。这次我们来了解UWP中的本地图片选取。

本地图片选取

在 MS 的 Docs 中,有 FileOpenPicker Class。我们来看看官档中对于这个类的描述和文件选取的例子:

FileOpenPicker
Represents a UI element that lets the user choose folders.

Pick a single file: complete code listing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>var picker = new Windows.Storage.Pickers.FileOpenPicker();
>picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
>picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
>picker.FileTypeFilter.Add(".jpg");
>picker.FileTypeFilter.Add(".jpeg");
>picker.FileTypeFilter.Add(".png");
>
>Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
>if (file != null) {
> // Application now has read/write access to the picked file
> this.textBlock.Text = "Picked photo: " + file.Name;
>}
>else {
> this.textBlock.Text = "Operation cancelled.";
>}
>

通过上面的例子,我们可以看到FileOpenPicker的工作流程:

  • 定义一个 FileOpenPicker 的实例
  • 设定 ViewMode,SuggestedStartLocation 和 FileTypeFilter 的值
    • ViewMode 给定工作时的视图模型
    • SuggestedStartLocation 指定启动位置
    • FileTypeFilter 给出选取的文件类型

FileOpenPicker 属性值设定完之后,它的 PickSingleFileAsync 方法可以返回我们选取的文件,其类型为 StorageFile。然后,利用一个 StorageFile 实例对选取的文件进行处理(注意判断选取的文件是否为空)。

接下来看看我们的 XAML 和 C# 代码:

1
2
3
4
5
<!--Xaml code for image-->
<Rectangle x:Name="Photo" Width="200" Height="200" RadiusX="150" RadiusY="150" VerticalAlignment="Center" HorizontalAlignment="Center"/>

<!--利用 rectangle 的 RadiusX 和 RadiusY 的属性进行圆形界面的设计
然后再用图片对界面进行填充,以此达到圆形图片的UI效果-->
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private async void Select_Photo(object sender, RoutedEventArgs e) {
FileOpenPicker picker = new FileOpenPicker();
// Initialize the picture file type to take
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".bmp");
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

StorageFile file = await picker.PickSingleFileAsync();

if (file != null) {
// Load the selected picture
IRandomAccessStream ir = await file.OpenAsync(FileAccessMode.Read);
BitmapImage bi = new BitmapImage();
await bi.SetSourceAsync(ir);
var brush = new ImageBrush
{
ImageSource = bi
};
Photo.Fill = brush;
}
}

是的,最后要解决的问题就是将选择的图片显示到我们的图片框中。
如果是使用 image 控件,那么在官档查一下它的 source 设置方法就可以了。这里讲一下怎么给 rectangle 控件设置它的填充图片 uri。

控件的 Fill 需要一个 ImageBrush 类型的值。ImageBrush 的 Source 需要使用 BitmapImage 来赋值。BitmapImage 有一个 接受 IRandomAccessStream 类型参数的 SetSourceAsync 的异步方法用来设置它的 source url。StorageFile 有一个 OpenAsync 的异步方法,可以获得文件的 url,并且是 IRandomAccessStream 类型(查阅官档到昏厥,并没有深究其中的一些细节,感兴趣的可以了解一下)。所以,这就有了最后的那段代码。

至此,本地图片的选取就完成啦。