缩放位图以适应允许的空间?

时间:2014-01-29 20:40:44

标签: android bitmap out-of-memory scale

在我的壁纸应用程序的XML i分界空间中,按钮和徽标左侧空间用于显示图片,根据它的大小,它可以变大或变小

XML演示:

  ....
  <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="115dp"
        android:orientation="horizontal" />
     <ImageView 
        android:src="@drawable/wal1"
        android:id="@+id/WPdisplay"
        android:layout_width="wrap_content"
        android:layout_height="0dip"   ///----> scale to fit the available space
        android:layout_gravity="center"
        android:layout_weight="1"
        android:contentDescription="@string/desc"  />
    <HorizontalScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center" >
  ....

一切都进行得很顺利,直到我遇到一堆内存错误,但我尝试使用 MainActivity 扩展位图以适应可用空间,以节省堆大小,我是怎么尝试的我无法使其适合可用空间。

这是 MainActivity代码

.....
public Bitmap decodeAndResizeFile(int resID) {
         try {
                // Decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(context.getResources(), resID, o);

     final int REQUIRED_SIZE = 100;
     int scale = 1;
     while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
         scale*=2;

     BitmapFactory.Options o2 = new BitmapFactory.Options();
     o2.inSampleSize = scale;
     return BitmapFactory.decodeResource(context.getResources(), resID, o2);

} finally {
        // return null;

 }
}

    Bitmap bmpp; 
    @Override
    public void onClick(View v) {
        Bitmap old_bm = null;
        switch (v.getId()){
        case R.id.WPimg1:
            old_bm = bmpp;
           //  display.setImageResource(R.drawable.wal1);
             toPhone = R.drawable.wal1;
             bmpp = decodeAndResizeFile(toPhone);
             display.setImageBitmap(bmpp);
             if (old_bm != null)
             {
                 old_bm.recycle();  //Recyle the old bitmap
                 old_bm = null;     //Clear the reference to allow GC to clean up fully
             }
             break;
      ......

有人可以向我提出任何想法吗?我如何适应可用空间?

0 个答案:

没有答案
相关问题