2013-06-05 47 views
2

我想設置大小更高的固定高度和寬度的ImageView的位圖,在XML固定的高度,並與大尺寸的位圖問題寬度imageview的

ImageView的

<ImageView 
     android:id="@+id/imgDisplay" 
     android:layout_width="320dp" 
     android:layout_height="180dp" 
     android:layout_marginLeft="10dp" 
     android:layout_marginTop="5dp" 
     android:contentDescription="@string/app_name" /> 

當我使用以下避免代碼錯誤,但形象出現模糊,因爲BitmapFactory.Options選項,

BitmapFactory.Options options = new BitmapFactory.Options(); 
      options.inPurgeable = true; 
      options.inSampleSize = 4; 
      Bitmap myBitmap = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/"+photo, options); 
      imgMainItem.setImageBitmap(myBitmap); 

還有什麼可設定更高的大小和f的圖像的選項ixed的高度和寬度請幫助

回答

2

請勿使用固定的樣本大小。計算你需要首先將樣本大小,就像這樣:

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 
     if (width > height) { 
      inSampleSize = Math.round((float)height/(float)reqHeight); 
     } else { 
      inSampleSize = Math.round((float)width/(float)reqWidth); 
     } 
    } 
    return inSampleSize; 
} 

然後,使用它像這樣:

String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/"+photo; 
final BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inJustDecodeBounds = true; 
BitmapFactory.decodeFile(path, options); 

// Calculate inSampleSize 
options.inSampleSize = calculateInSampleSize(options, width, height); 

options.inJustDecodeBounds = false; 
Bitmap myBitmap = BitmapFactory.decodeFile(path, options); 
imgMainItem.setImageBitmap(myBitmap); 

widthheight是您需要的寬度和高度,以像素爲單位。

如果你的位圖是一個很多小於你想要的大小,你不能真正擴展它,而不會模糊。使用更高質量的位圖。

+0

-Ken Wolf在40144912字節的分配中沒有發現內存不足的錯誤。 – hemant

+0

你爲reqWidth和reqHeight放了什麼值? –

+0

BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = calculateInSampleSize(options,300,250); – hemant

相關問題