2012-12-22 23 views
1

因此,我對Android開發相當陌生,而且使用ImageViews時遇到了一個奇怪現象。任何指針或建議將非常歡迎!ImageView顯示奇怪的全綵色盒子

我正在爲我的ImageViews動態設置位圖,這是sorta工作。除了它們有時只顯示圖像外,其餘時間我都會用下面看到的近似圖像顏色進行全綵色填充。

Screenshot

我認爲他們正在縮放正確使用此代碼,我在Android論壇上得到的,所以我不認爲我遇到的內存問題....

public static Bitmap decodeSampledBitmapFromStream(InputStream inputStream, int reqWidth, int reqHeight) { 

     // First decode with inJustDecodeBounds=true to check dimensions 
     final BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeStream(inputStream,null,options); 

     // Calculate inSampleSize 
     options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

     // Decode bitmap with inSampleSize set 
     options.inJustDecodeBounds = false; 
     return BitmapFactory.decodeStream(inputStream,null,options); 
    } 

回答

1

後在這個問題上花了很多時間,我終於明白,因爲我使用AsyncTask來加載這些位圖,它們偶爾會比主UI線程更快。當我打電話給myImageView.getHeight() & width()時,這就搞砸了我。

所以這裏就是我與希望,它可能幫助別人前進的道路上還提出瞭解決方案:

public class DecodeTask extends AsyncTask<String, Void, Bitmap> { 

public ImageView currentImage; 
private static AssetManager mManager; 

public DecodeTask(ImageView iv, AssetManager inputManager) { 
    currentImage = iv; 
    mManager = inputManager; 
} 

protected Bitmap doInBackground(String... params) { 

    int bottomOut = 1000; 
    while(currentImage.getMeasuredWidth() == 0 && currentImage.getMeasuredHeight() == 0 && (--bottomOut) > 0) 
    { 
     try { 
      Thread.sleep(10); 
     } catch (InterruptedException e1) { 
      e1.printStackTrace(); 
     } 
    } 

    InputStream iStream = null; 
    Bitmap bitmap = null; 
    try { 
     iStream = mManager.open("photos" + File.separator + params[0]); 

     bitmap = ImageUtils.decodeSampledBitmapFromStream(iStream, currentImage.getMeasuredWidth(), currentImage.getMeasuredHeight()); 

     iStream.close(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return bitmap; 
} 

@Override 
protected void onPostExecute(Bitmap result) { 
    if(currentImage != null) { 
     currentImage.setImageBitmap(result); 
     currentImage.invalidate(); 
    } 
} 

}