標籤:des android blog http io ar 使用 sp java
問題:如果圖片很大,全部載入記憶體,而顯示屏又不大,那麼再大的圖片也不會提高視覺效果的,而且會消耗無謂的記憶體。
解決辦法就是根據實際需要多大的圖片,然後動態計算應該載入多大的圖片;但是因為不太可能圖片大小和實際需要的大小一致,故此需要載入圖片大小為一個2的某次方的值,而大於實際需要的大小。
,載入一個微縮圖大小為100*100
建立一個項目,
參考Google上的方法:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html#load-bitmap
建立一個類,以便調用其中的函數處理圖片資源,全部代碼如下:
package bill.su.loadbitmap;import android.content.res.Resources;import android.graphics.Bitmap;import android.graphics.BitmapFactory;public class BitmapUtils {public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {// Raw height and width of imagefinal int height = options.outHeight;final int width = options.outWidth;int inSampleSize = 1;if (height > reqHeight || width > reqWidth) {final int halfHeight = height / 2;final int halfWidth = width / 2;// Calculate the largest inSampleSize value that is a power of 2 and// keeps both// height and width larger than the requested height and width.while ((halfHeight / inSampleSize) > reqHeight&& (halfWidth / inSampleSize) > reqWidth) {inSampleSize *= 2;}}return inSampleSize;}public static Bitmap decodeSampledBitmapFromResource(Resources res,int resId, int reqWidth, int reqHeight) {// First decode with inJustDecodeBounds=true to check dimensionsfinal BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;BitmapFactory.decodeResource(res, resId, options);// Calculate inSampleSizeoptions.inSampleSize = calculateInSampleSize(options, reqWidth,reqHeight);// Decode bitmap with inSampleSize setoptions.inJustDecodeBounds = false;return BitmapFactory.decodeResource(res, resId, options);}}
主介面的xml代碼:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="bill.su.loadbitmap.MainActivity" > <ImageView android:id="@+id/pandaImageView" android:layout_width="100px" android:layout_height="100px" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" /></RelativeLayout>
使用ImageView來顯示圖片
主介面的邏輯代碼添加代碼:
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ImageView imageView = (ImageView) findViewById(R.id.pandaImageView);imageView.setImageBitmap(BitmapUtils.decodeSampledBitmapFromResource(getResources(), R.drawable.panda, 100, 100));}注意R.drawable.panda是怎麼來的。只要在專案檔夾中的res檔案夾的drawable檔案夾添加一個圖片命名為panda,在Eclipse重新整理項目就會顯示這個id了。如果沒有drawable這個檔案夾也不要緊,直接自己建立一個檔案夾就可以了。
如果圖片沒有顯示,很可能是圖片資源不存在,這樣項目是不會提示錯誤的,直接沒有顯示出來。
看看項目結構圖,就知道如何建立這個項目了:
這裡主要學習的代碼是BitmapUtils中的代碼,這樣已經封裝好了,以後可以當做自己的一個資源類調用了。
Android百議程序:高效載入大圖片