Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 用 Intent 輕鬆讀取圖庫圖片

編輯:關於 Android 程式設計

本文實例演示如何從圖庫(Gallery)中讀取圖像,並用 ImageView 將它顯示出來,供大家參考。運行本示例前,建議先用相機拍攝幾張照片放進圖庫,以便測試。

運行截圖

主要設計步驟

步驟一:新增佈局檔 ch1203_ReadGallery.axml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://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>

步驟二:新增 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); } } } } 

關鍵在於透過 Intent 設定 ActionGetContent 與 image/* 類型,呼叫系統的挑選器開啟圖庫,再利用 onActivityResult 回呼取得所選圖片的 URI,交給 ImageView 顯示即可。

以上就是本文的全部內容,希望對大家的學習有所幫助,也歡迎多多支持本站。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved