ImageView是基礎的控制項,它是android.widget.ImageView的繼承類。
XML片段
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- 指定資源id: @drawable/xxxxx -->
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ui_image1"
android:src="@drawable/ic_launcher" />
<!-- 顯示色塊 -->
<ImageView android:layout_width="125dip"
android:layout_height="25dip"
android:id="@+id/ui_image2"
android:src="#555555"
android:contentDescription="set pure color"/>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- 這三個圖來源於同一個128×128的png表徵圖,前兩者指定長、寬時,皆比原圖要小,系統採用等比縮小的方式適配指定size -->
<ImageView android:layout_width="25dip"
android:layout_height="25dip"
android:src="@drawable/png0441"/>
<ImageView android:layout_width="48dip"
android:layout_height="48dip"
android:src="@drawable/png0441"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/png0441" />
</LinearLayout>
<!-- 對下面的圖,我們設定圖片縮小的方式,fitXY,填滿整個size。此外我還是實驗了兩layout_width和layout_height設定為wrap_content,而另外設定了maxWidth和maxHeight,但是發現maxWidth/Height並不起作用,仍是原圖大小呈現,這點和Pro Android 4.0書中所言不同,關於此功能,慎用
-->
<ImageView android:layout_width="60dip"
android:layout_height="30dip"
android:src="@drawable/png0441"
android:scaleType="fitXY" />
<!-- 這裡我們沒有設定android:src,但是給了一個id號,用於等會在代碼進行設定 -->
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ui_image3" />
代碼設定ImageView
在XML中ui_image3沒有設定具體的src,可以在代碼中通過若干中方法設定。
方式1:設定資源的ID
ImageView image = (ImageView)findViewById(R.id.ui_image3);
image.setImageResource(R.drawable.ic_launcher);
方式2:通過Bitmap
ImageView image = (ImageView)findViewById(R.id.ui_image3);
Bitmap bm = BitmapFactory.decodeResource(this.getResources(), R.drawable.png02);
//在這裡可以加入對Bitmap的處理代碼 ... ...
image.setImageBitmap(bm);
方式3:通過檔案
對於模擬器,我們通過命令列以adb push的方式將圖片檔案放入檔案系統的某個位置,例如sdcard中,如所示:
ImageView image = (ImageView)findViewById(R.id.ui_image3);
try{
String filename = Environment.getExternalStorageDirectory()+ "/wei/sunflower.jpg";
image.setImageDrawable(Drawable.createFromPath(filename));
}catch(Exception e){
Log.e("wei",e.toString());
}
方式4:通過Uri方式
ImageView image = (ImageView)findViewById(R.id.ui_image3);
image.setImageURI(Uri.parse("file://mnt/sdcard/wei/logo.jpg"));
//只能是本機存放區
注意URI方式只限於本機存放區,不能是遠端儲存,如果我們設定了web URI,系統會報以下錯誤:
其他
如果我們希望圖片來自remote,可以利用BitmapFactory.decodeStream(InputStream is),然後將Bitmap放入ImageView中。
相關連結:
我的Android開發相關文章