Android利用Intent實現讀取圖片操作

Android利用Intent實現讀取圖片操作

本文例項演示如何從相簿(Gallery)中讀取影象並用ImageView將它顯示出來,供大家參考,具體內容如下
執行本示例前,需要先利用相機模擬拍攝一些圖片到相簿中。

1、執行截圖

  

2、主要設計步驟

(1)新增ch1203_ReadGallery.axml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@ id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:layout_gravity="center"
android:text="從相簿中挑選一幅圖片" />
<TextView
android:text="你挑選的圖片為:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@ id/textView1"
android:layout_gravity="center"
android:layout_margin="30dp" />
<ImageView
android:id="@ id/myImageView"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

(2)新增ch1203ReadGallery.cs


using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Widget;
namespace MyDemos.SrcDemos
{
[Activity(Label = "【例12-3】讀取相簿圖片")]
public class ch1203ReadGallery : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.ch1203_ReadGallery);
var btn1 = FindViewById<Button>(Resource.Id.btn1);
btn1.Click  = delegate {
var imageIntent = new Intent();
imageIntent.SetType("image/*");
imageIntent.SetAction(Intent.ActionGetContent);
StartActivityForResult( Intent.CreateChooser(imageIntent, "選擇的圖片:"), 0);
};
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok)
{
var imageView = FindViewById<ImageView>(Resource.Id.myImageView);
imageView.SetImageURI(data.Data);
}
}
}
}