2013-11-23 38 views
0

Google建議從縮小的資源加載位圖,具體取決於實際的ImageView尺寸(谷歌Google開發人員指南中的「高效加載大型位圖」)。因此,在解碼位圖之前,我必須知道ImageView的寬度和高度。Android Imageview:測量未指定來計算位圖尺寸

我的代碼看起來像下面發佈的代碼。 decodeSampledBitmapFromResources將位圖作爲資源中存儲的版本的縮小版本返回。

public void onCreate(Bundle savedInstanceSate) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.myLayout) 

    ImageView imageView = (ImageView) findViewById(R.id.myImageView); 

    /** 
    At this point, I need to calculate width and height of the ImageView. 
    **/ 

    Bitmap bitmap = MyBitmapManager.decodeSampledBitmapFromResource(
         getResources(), R.drawable.my_icon, width, height); 
    imageView.setImageBitmap(bitmap); 
} 

問題是,因爲我在onCreate中,我的ImageView沒有任何寬度和高度。的getWidth()和getHeight()剛剛返回0。我偶然發現了這個代碼來計算視圖的大小之前,它實際上是得出:

ImageView v = findViewById(R.id.myImageView); 
v.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); 
int width = v.getMeasuredWidth(); 
int height = v.getMeasuredHeight(); 

這是適合我的情況?我試過了,上面的代碼返回的寬度和高度值似乎是正確的,但林不知道這是否是正確的方式來做到這一點。

更新: 經過一些更多的測試,這似乎不工作。 在上面的例子中,我使用一個尺寸爲192x192像素的PNG。 如上所示測量ImageView後,我得到的測量尺寸爲128x128。 如果我在調用getWidth()和getHeight()之後將位圖設置爲imageview,則尺寸爲100x100。 因此在這種情況下,圖像從192x192縮小到128x128,但不是100x100,因爲它應該是。

看起來Measurespec.UNSPECIFIED總是返回的尺寸大於它們在結尾處的尺寸。

由於提前,

danijoo

回答

0

我得到了解決我自己這一點:

ViewTreeObserver vto = imageView.getViewTreeObserver(); 
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { 
    public boolean onPreDraw(){ 
     // at this point, true width and height are already determined 
     int width = imageView.getMeasuredWidth(); 
     int height = imageView.getMeasuredHeight(); 

     Bitmap bitmap = MyBitmapManager.decodeSampledBitmapFromResource(
         getResources(), R.drawable.my_icon, width, height); 
     imageView.setImageBitmap(bitmap); 

     // this is important because onPreDrawn is fired multiple times 
     imageView.getViewTreeObserver().removeOnPreDrawListener(this); 
     return true; 
    } 
}