2014-02-18 56 views
0

的另一個圖像我有一個ImageView的一個RelativeLayout的,並在設計時,我從資源加載144x144 PNG圖像,一切看起來不錯:ImageView的收縮時,圖像替換相同尺寸

enter image description here

現在,在代碼中,我拍照與照相機和它裁剪到144x144並將其加載到圖像視圖:

imageViewMyPicture.setImageBitmap(bitmap); 

但現在ImageView的收縮:

enter image description here

兩張圖片都有100%相同的尺寸,144x144,如果我在設計時將第二張圖片加載到imageView中,則尺寸正常加載。

我在做什麼錯?

回答

1

您在創建縮放位圖時需要考慮密度。由於您的ImageView有設置新的位圖前正確的尺寸,你的情況,你可以只縮放新Bitmap時使用ImageView的尺寸...例如:

我假設你正在使用Uri小號從文件系統中獲取存儲的圖像。如果您使用File s,只需使用Uri.fromFile(file)即可獲得Uri。我通常使用的AsyncTask做到這一點,因爲你應該做的位圖處理掉主線程......這裏的一些須藤代碼(不是在AsyncTask爲了簡單,但容易重構):

//Somewhere in your Activity 

public void scaleAndSetBitmap(ImageView imageView, Uri uri){ 
      InputStream stream = null; 
      Bitmap bitmap = null; 

      try { 
      stream = getContentResolver().openInputStream(uri); 
      bitmap = BitmapFactory.decodeStream(stream, null, options); 

       if (image_view != null && bitmap != null) { 
       bitmap = Bitmap.createScaledBitmap(bitmap, image_view.getWidth(), image_view.getHeight(), true); 
       image_view.setImageBitmap(bitmap); 
       } 
      } catch(Exception e){ 
       e.printStackTrace(); 
       return; 
      } finally { 
       try{ 
        stream.close(); 
       } catch(IOException i){ 
        return; 
       } 
      } 
} 
1

確保在加載圖像時考慮到您正在運行的設備的密度。你認爲你有144x144,但這可能是原始的圖像文件,但是當放在高密度的設備上時,它將被渲染成接近200x200。然後,當您將相機圖像剪裁爲144x144時,您將獲得原始尺寸,但不是調整後的密度尺寸。確保你獲得的簡單方法是使用資源讀取圖像:

例如,使用此簽名加載位圖意味着應用程序將以適當的密度讀取圖像,併爲該設備提供所需的大小。

selectImg = BitmapFactory.decodeResource(getResources(), R.drawable.drop_device);