2013-04-27 53 views
4

我正在嘗試計算此圖片的尺寸,該尺寸將使用此線從網上下載imgLoader.DisplayImage(url, R.drawable.thumbnail_background, image);。 問題是orgHeight變成零,你不能被零除。但爲什麼這是orgHeight 0?正在更新layoutParams無法正常工作

// Add the imageview and calculate its dimensions 
     //assuming your layout is in a LinearLayout as its root 
     LinearLayout layout = (LinearLayout)findViewById(R.id.layout); 

     ImageView image = (ImageView)findViewById(R.id.photo); 

     ImageLoader imgLoader = new ImageLoader(getApplicationContext()); 
     imgLoader.DisplayImage(url, R.drawable.thumbnail_background, image); 

     int newHeight = getWindowManager().getDefaultDisplay().getHeight()/2; 
     int orgWidth = image.getWidth(); 
     int orgHeight = image.getHeight(); 

     //double check my math, this should be right, though 
     int newWidth = (int) Math.floor((orgWidth * newHeight)/orgHeight); 

     //Use RelativeLayout.LayoutParams if your parent is a RelativeLayout 
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
      newWidth, newHeight); 
     image.setLayoutParams(params); 
     image.setScaleType(ImageView.ScaleType.CENTER_CROP); 
     layout.updateViewLayout(image, params);  

我ImageView的XML是這樣的:

<ImageView 
      android:id="@+id/photo" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
     /> 

回答

7

的意見尚未敷設在onCreate()方法,因此它們的尺寸都是0發帖RunnableonCreate()得到正確的價值觀:

image.post(new Runnable() { 

@Override 
public void run() { 
    int newHeight = getWindowManager().getDefaultDisplay().getHeight()/2; 
    int orgWidth = image.getWidth(); 
    int orgHeight = image.getHeight(); 

    //double check my math, this should be right, though 
    int newWidth = (int) Math.floor((orgWidth * newHeight)/orgHeight); 

    //Use RelativeLayout.LayoutParams if your parent is a RelativeLayout 
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
     newWidth, newHeight); 
    image.setLayoutParams(params); 
    image.setScaleType(ImageView.ScaleType.CENTER_CROP); 
    layout.updateViewLayout(image, params);  
} 

}); 
+0

謝謝,它的工作原理,但現在我有一個更多的問題,畫面的高度計算不正確,我有 - 它看起來像 - 填充在頂部和底部。 – user6827 2013-04-27 13:52:27

+0

或左右* – user6827 2013-04-27 13:58:01

+0

@ user6827嘗試使用'ImageView.ScaleType.FIT_XY'。 – Luksprog 2013-04-27 14:04:06